skip to Main Content

I’m using jwt to decode my token to check if it is expired or not, I get error on crypto module not found.

  import jwt from 'jsonwebtoken';

const checkToken = token => { 
   try { 
       const decodedToken = jwt.decode(token); 
       const experiationTime = decodedToken.exp;
       const expirationDate = new Date(experiationTime * 1000);

       if (expirationDate > currentDate) {
          console.log('Token is still valid', expirationDate);
          return true;
        } else {
          console.log('Token is expired', expirationDate);
          return false;
        }
     }
   catch(err){
       console.log(err)
   }
 }

I get the followin error:
Unable to resolve module crypto from <app_Name>node_modulesjsonwebtokenverify.js: crypto could not be found within the project or in these directories:

node_modulesjsonwebtokennode_modules
node_modules
7 | const PS_SUPPORTED = require(‘./lib/psSupported’);
8 | const jws = require(‘jws’);

9 | const {KeyObject, createSecretKey, createPublicKey} = require("crypto");

Since React Native does not use the Node runtime environment and thus does not have access to specific libraries such as ‘crypto’,So I installed nodeify & in package.json I include the below statment

  1. npx rn-nodeify –install

  2. script:{

    "postinstall": "node_modules/.bin/rn-nodeify –install crypto,assert,url,stream,events –hack"
    }

But still getting the same error.

2

Answers


  1. you can import import './shim.js' before const {KeyObject, createSecretKey, createPublicKey} = require("crypto"); and patch it.

    you can check this to how can configure it:
    Resolve Node.js crypto module in React Native

    Login or Signup to reply.
  2. Try jwtDecode package instead available in npm
    https://www.npmjs.com/package/jwt-decode

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search