76

I dont want my token to get expire and shold be valid forever.

var token = jwt.sign({email_id:'123@gmail.com'}, "Stack", {

                        expiresIn: '24h' // expires in 24 hours

                         });

In above code i have given for 24 hours.. I do not want my token to get expire. What shall be done for this?

Jagadeesh
  • 1,967
  • 8
  • 24
  • 47

5 Answers5

78

The exp claim of a JWT is optional. If a token does not have it, it is considered that it does not expire

According to the documentation of https://www.npmjs.com/package/jsonwebtoken the expiresIn field does not have a default value either, so just omit it.

There are no default values for expiresIn, notBefore, audience, subject, issuer. These claims can also be provided in the payload directly with exp, nbf, aud, sub and iss respectively, but you can't include them in both places.

var token = jwt.sign({email_id:'123@gmail.com'}, "Stack", {});
pedrofb
  • 37,271
  • 5
  • 94
  • 142
58

To set expirey time in days: try this

 var token = jwt.sign({email_id:'123@gmail.com'}, "Stack", {

           expiresIn: '365d' // expires in 365 days

      });

"expiresIn" should be a number of seconds or string that repesents a timespan eg: "1d", "20h",

Docs: jsonwebtoken

Ved
  • 11,837
  • 5
  • 42
  • 60
45

You can set expire time in number or string :

expressed in seconds or a string describing a time span zeit/ms.
Eg: 60, "2 days", "10h", "7d".

A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc),
otherwise milliseconds unit is used by default ("120" is equal to "120ms").

 var token = jwt.sign({email_id:'123@gmail.com'}, "Stack", {
        expiresIn: "10h" // it will be expired after 10 hours
        //expiresIn: "20d" // it will be expired after 20 days
        //expiresIn: 120 // it will be expired after 120ms
        //expiresIn: "120s" // it will be expired after 120s
 });
Abolfazl Roshanzamir
  • 12,730
  • 5
  • 63
  • 79
10

You can save your settings in a config file. expires in days use d after your desire days like after 90 days should be: 90d for hours use h for example 20h

you can use milliseconds also, for example, after 4102444800ms

config.env

JWT_SECRET = my-32-character-ultra-secure-and-ultra-long-secret
JWT_EXPIRES_IN = 90d

authController.js

const signToken = (id) => {
  return jwt.sign({ id: id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });
};

const signIn = (user) =>{
    const token = signToken(user._id);
}
Rafiq
  • 8,987
  • 4
  • 35
  • 35
  • is expiresIn in jwt different from the maxAge in cookies? I'm sending the jwt as a cookie to the client but it seems like setting expiresIn doesn't affect the cookie – The.Wolfgang.Grimmer Oct 13 '20 at 03:36
8
  jwt.sign(contentToEncrypt, SECRET_KEY, { expiresIn: '365d' });
Shubham Kakkar
  • 581
  • 6
  • 4