JSON Web Token (JWT) set expire time in node js
Setting Expiry Time for JSON Web Token (JWT) in Node.js
To set the expiry time for a JSON Web Token (JWT) in Node.js, you can follow these steps:
- Generate a New JWT:
- To generate a new JWT, you can use the
jsonwebtoken
library in Node.js. This library allows you to create and verify JWTs. - Here's an example of how to create a JWT with an expiry time of 1 hour:
javascript const jwt = require('jsonwebtoken'); const token = jwt.sign({ user: 'username' }, 'secret', { expiresIn: '1h' });
- Specify Expiry Time:
- When creating the JWT, you can specify the expiry time using the
expiresIn
option in thejsonwebtoken.sign
method. The value for
expiresIn
can be a number of seconds or a string describing a time span. For example, '1h' for 1 hour, '7d' for 7 days, etc.Use the JWT:
- Once the JWT is created with the specified expiry time, you can use it for authentication and authorization in your Node.js application.
- When a client sends the JWT for authentication, you can verify its validity and expiry using the
jsonwebtoken.verify
method.
By following these steps, you can set the expiry time for a JSON Web Token (JWT) in your Node.js application.