jsonwebtoken in react have an error "Cannot read property '2' of null"

Viewed 815

I have this task in our React project that needs to encrypt the object inside a state using jwt. It throws an error that says "Cannot read property '2' of null" while I use the .sign() method and including the RS256 algorithm.

Here is a sample of what I am doing .

import { useState } from "react";
import "./styles.css";

import jwt from "jsonwebtoken";

import configData from "./conf.json";

export default function App() {
  const [state] = useState({
    name: "John",
    age: 22,
    sex: "Male"
  });

  const stateHashed = jwt.sign(state, configData.SECRET_KEY, {
    algorithm: "RS256"
  });

  console.log(configData.SECRET_KEY);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <h1>Hashed key</h1>
      <h3>{stateHashed}</h3>
    </div>
  );
}

Here is the conf.json file for the secret key

{
  "SECRET_KEY": "exDj"
}

Thanks for anyone who can help.

1 Answers

I fix my issue. I'm going to share so anyone with the same case as me will have an idea of my solution.

I've created a private.key file in the root folder of the react project and included the RSA Generated string inside the file. To get the private.key file, I did define the fs module of nodeJs in the App

import { useState } from "react";
import "./styles.css";

import jwt from "jsonwebtoken";
import jwt_decode from "jwt-decode";

//Added fs library
const fs = require('fs');

export default function App() {
  const [state] = useState({
    name: "John",
    age: 22,
    sex: "Male"
  });

  // private.key file in the root foldef 
  // RSA Key Generator 
  const privateKey = fs.readFileSync('private.key');

  //Hash the data using jwt
  const stateHashed = jwt.sign(state, privateKey, {
    algorithm: "RS256"
  });

  const stateHashedDecoded = jwt_decode(stateHashed);

  console.log(jwt_decode(stateHashed))

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <h1>Hashed key</h1>
      <h3>{stateHashed}</h3>

      <h1>String inside the hash</h1>
      <h3>{stateHashedDecoded.name + " " + stateHashedDecoded.age + " " + stateHashedDecoded.sex}</h3>
    </div>
  );
}

To get a generated RSA. You may check this link.

http://travistidwell.com/jsencrypt/demo/

For anyone who wants to view the simple project

https://codesandbox.io/live/hk2sxv3

Related