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

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

var token = jwt.sign({email_id:''}, "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?

8

5 Answers

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 documentation of 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 in both places.

var token = jwt.sign({email_id:''}, "Stack", {}); 

To set expirey time in days: try this

 var token = jwt.sign({email_id:''}, "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

3

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:''}, "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 }); 
1

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like