Search code examples
javascriptreactjsjwt

Right-hand side of 'instanceof' is not an object, jsonwebtoken


I am going to create a token of form data using jsonwebtoken in my React project.

import jwt from 'jsonwebtoken';

const MyForm = () => {
    const submitForm = (e) => {
       e.preventDefault();
       const data = { name: 'name', email: 'email', subject: 'subject', message: 'message' };
       const token = jwt.sign(data, 'qwerty');
       console.log(token);
    }
    return(
        <form onSubmit={submitForm}>
            ...
        </form>
    );
}
export default MyForm;

Following error is occurred.

TypeError: Right-hand side of 'instanceof' is not an object
push../node_modules/jsonwebtoken/sign.js.module.exports [as sign]
../node_modules/jsonwebtoken/sign.js:108
  105 |   return failure(new Error('secretOrPrivateKey must have a value'));
  106 | }
  107 | 
> 108 | if (secretOrPrivateKey != null && !(secretOrPrivateKey instanceof KeyObject)) {
      | ^  109 |   try {
  110 |     secretOrPrivateKey = createPrivateKey(secretOrPrivateKey)
  111 |   } catch (_) {
View compiled
submitEmail
../MyForm.js:22
  19 |    e.preventDefault();
  20 |    
  21 |    const data = { name: 'name', email: 'email', subject: 'subject', message: 'message' };
> 22 |    const token = jwt.sign(data, 'qwerty');
     | ^  23 |    console.log(token)
  24 | 
  25 | 

Why is this giving me that error? I have tried to solve this problem but no results yet.
And any help to fix it is appreciated. Thanks.


Solution

  • I had the same issue. The issue being that version 9.0.0 of the jsonwebtoken package does not support node version 11 and below, so I solved it by downgrading the version of the jsonwebtoken package.

    I did so by changing the jsonwebtoken dependency from 9.0.0 to 8.5.1 inside the package.json file, then I ran npm update inside my terminal.

    Upgrading your node version might be recommended here, but I haven't quite managed to update my node version because of an npm issue, so this is only a workaround.

    Checkout the following article explaining the migration from v8 to v9 of the jsonwebtoken package. https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v8-to-v9