How to set jwt token expiry time to maximum in nodejs?

Viewed 205779

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?

5 Answers

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
 });

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);
}
  jwt.sign(contentToEncrypt, SECRET_KEY, { expiresIn: '365d' });
Related