jwt-decode: Invalid token specified: Cannot read property 'replace' of undefined

I get Invalid token specified: Cannot read property ‘replace’ of undefined:

Object.<anonymous> ../node_modules/jwt-decode/lib/index.js 9:0
Showing original source content from sourcemap
'use strict';
 var base64_url_decode = require('./base64_url_decode');
 function InvalidTokenError(message) {
  this.message = message;
}
 InvalidTokenError.prototype = new Error();
InvalidTokenError.prototype.name = 'InvalidTokenError';
 
module.exports = function(token, options) {
    if (typeof token !== 'string') {
      throw new InvalidTokenError('Invalid token specified');
    }

Can i get any help ASAP please?!

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 16 (2 by maintainers)

Commits related to this issue

Most upvoted comments

I had same problem as well, If you are login to the App and you did play with token in backend(postman). then token mismatch might happen so you take recent token from postman and add it to the localstorage in the browser, which was in undefined.

In my case, I’m attempting to protect the client-side app against “corrupt” cookies (tokens that aren’t in JWT format) in the event a user messes with their cookies. In the moment I’m decoding, if the token can’t be parsed, the error thrown breaks the app, despite my attempt to catch.

export const isAccessTokenExpired = (): boolean => {
  if (!isAccessTokenSet()) {
    // if it doesn't exist, we'll also consider it expired
    return true;
  }

  // ensure it's actually JWT format
  try {
    jwt_decode(getAccessToken());
  } catch (error) {
    console.log('👾 invalid token format', error);
    return true;
  }

  const token = jwt_decode(getAccessToken());
  const { exp } = token;
  return Math.round(Date.now() / 1000) >= exp ? true : false;
};

Upon attempting to decode a non-JWT format value, the catch triggers, but the error still shows as Uncaught and breaks runtime:

👾 invalid token format InvalidTokenError {message: "Invalid token specified: Cannot read property 'replace' of undefined"}

Uncaught InvalidTokenError {message: "Invalid token specified: Cannot read property 'replace' of undefined"}
message: "Invalid token specified: Cannot read property 'replace' of undefined"

I was having this issue when using jwtDecode with a token issued from our Auth0 tenant.

Ensure your “audience” option in your Auth0 config exists and is correct. If it is not, you get back a token in the incorrect format.

You need to post a little more context when posting an issue. How are you using jwtDecode? What format is the token you are passing in?

For future reference: this error occurs when the token does not adhere to the expected format of a jwt token

For example I ran into this in unit tests where the token was mocked with something like “FAKE_TOKEN” Currently this lib assumes a valid syntax for the token meaning the token must include a single dot (.) and the part after the dot must be a valid base64 encode otherwise you’d get these errors.

Adding a check on undefined in base64_url_decode would solve this and could give developers a good clue to what is going wrong.

For now I replaced my FAKE_TOKEN with FAKE.eyJmYWtlIjogdHJ1ZX0= which causes the JwtDecode to succeed

Hey friends,

I’ve been trying to reproduce all of the errors mentioned above. When using the decode function, make sure:

  • The token is not undefined
  • The token is a valid JSON Web Token,
  • You remove the bearer authentication type, as this is not part of the token but indicates the authentication scheme
  • The token header and payload are valid base64 encoded, this means the token can only contain these characters: a–z, A–Z, 0–9, and -_.
  • When using a try/catch block to catch the invalid token error, make sure you’re not trying to decode the token or header somewhere else in your code, as the error will only be caught in the try/catch block.

I feel it is only happening because token is set to undefined. Either clear out that token from inspect menu and refresh your application. It may work then.

in my case, I had to do some manipulation to remove the word "Bearer " out of the token string

try { // console.log('TOKEN: ’ + token.replace('Bearer ', ‘’)) tokenExpires = decode(token.replace('Bearer ', ‘’), { header: true }).exp } catch (error) { // console.log('TOKEN Error: ’ + JSON.stringify(error)) // Bad token so send back expired; we need a new one return true }