Search code examples
javascriptreactjsjwt

Can't import jwt-decode in JavaScript file in React project


I created a React app and I try to make a separate file for functions. I required 'jwt-decode' library like that:

const jwt_decode = require("jwt-decode");

After that I used it like that:

const verifyToken = (token) => { console.log(jwt_decode(token)); };

And exported like that:

module.exports = { verifyToken };

When I tried to use it in my react page, I saw this error in the console:

Uncaught TypeError: jwt_decode is not a function

What I did wrong?


Solution

  • It looks like you are trying to use CommonJS require syntax in a React app that is likely using ES6 import syntax.

    Try changing your code to the following:

    import jwt_decode from "jwt-decode";
    
    const verifyToken = (token) => { console.log(jwt_decode(token)); };
    
    export default { verifyToken };
    

    And then in your React page, use:

    import verifyToken from './path/to/your/file';
    

    It works to me!