How Long is a JWT Token Valid ?
Last Updated :
10 Jun, 2024
JSON Web Tokens (JWTs) are widely used for authentication and authorization in modern web applications and APIs. One crucial aspect of JWTs is their validity period, which determines how long a token remains valid after it has been issued. In this article, we'll delve into the factors influencing the validity period of JWT tokens and best practices for setting their expiration time.
What is a JWT Token?
Before discussing the validity period, let's briefly review what a JWT token is. A JSON Web Token (JWT) is a compact, URL-safe means of representing claims securely between two parties. It comprises three sections: a header, a payload, and a signature. The payload contains the claims, which are statements about an entity (typically, the user) and additional data. Claims can include information such as the user's identity, permissions, and expiration time.
Importance of Validity Period
The validity period of a JWT token is crucial for security and access control. It ensures that tokens have a limited lifespan, reducing the risk of unauthorized access if a token is compromised. Setting an appropriate expiration time for JWT tokens is essential for balancing security requirements with user convenience and system performance.
The sign() method of the JSON Webtoken library is used for creating a token that accepts certain information as parameter objects and returns the generated token. Â
Syntax:
jwt.sign(payload, secretOrPrivateKey, [options, callback])
Parameters:
- payload: It is the information to be encrypted in the token
- secretKey: It is the signature or can say a code that is used to identify the authenticity of the token.
- options: In the option, we pass certain information about the token and that's the place where we provide the duration of the token up to which it will be valid.
Return type:
This method will return JWT token
Example: Implementation to create a token with 10 minutes expiry.
Steps to Implement JWT Token with Expiry
Step 1: Create a node project
As we are working on a node library it is a mandatory step to create a node project, write npm init in the terminal. It will ask for a few configurations about your project which is super easy to provide.
npm init
Step 2: Install the "jsonwebtoken" Package
Before going to write the JWT code we must have to install the package,Â
npm install jsonwebtoken
This would be our project structure after installation where node_modules contain the modules and package.json stores the description of the project. Also, we have created an app.js file to write the entire code.Â
Project Structure:

Step 3: Creating JWT token with a definite expire time.
There are two methods of registering the expiry of the token both are shown below with an explanation.Â
- Creating an expression of an expiry time.
- Providing expiry time of JWT token in the options argument of the method.
Approach 1: There exists a key exp in which we can provide the number of seconds since the epoch and the token will be valid till those seconds.
JavaScript
// Importing module
const jwt = require('jsonwebtoken');
const token = jwt.sign({
// Expression for initialising expiry time
exp: Math.floor(Date.now() / 1000) + (10 * 60),
data: 'Token Data'
}, 'secretKey');
const date = new Date();
console.log(`Token Generated at:- ${date.getHours()}
:${date.getMinutes()}
:${date.getSeconds()}`);
// Printing the JWT token
console.log(token);
 Output:

Approach 2: In this method, we can pass the time to expiresIn key in the options, it requires the number of seconds till the token will remain valid or the string of duration as '1h', Â '2h', '10m', etc.
JavaScript
// Importing module
const jwt = require('jsonwebtoken');
const token = jwt.sign({
// Assigning data value
data: 'Token Data'
}, 'secretKey', {
expiresIn: '10m'
});
const date = new Date();
console.log(`Token Generated at:- ${date.getHours()}
:${date.getMinutes()}
:${date.getSeconds()}`);
// Printing JWT token
console.log(token);
Output:

Step 4: Verify the token in terms of expiry duration
We have successfully generated the token now it's time to verify whether the code is working in its intended way or not.Â
JavaScript
//Importing module
const jwt = require('jsonwebtoken');
// JWT token
const token =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Mzc4NjgxMzMsImRhdGWf"
const date = new Date();
// Verifying the JWT token
jwt.verify(token, 'secretKey', function(err, decoded) {
if (err) {
console.log(`${date.getHours()}:${date.getMinutes()}
:${date.getSeconds()}`);
console.log(err);
}
else {
console.log(`${date.getHours()}:${date.getMinutes()}
:${date.getSeconds()}`);
console.log("Token verifified successfully");
}
});
Before 10 minutes:
Output 1: Here we are checking before 10 minutes of generating token, as expected the else block of code will work.

After 10 minutes:
Output 2: Here we are checking once the token is expired, the TokenExpirationError will be thrown in this case.Â

Factors Influencing Validity Period
Several factors influence the validity period of JWT tokens:
- Security Requirements: The sensitivity of the data and the security policies of the application or organization influence the choice of token validity period. More sensitive operations may require shorter-lived tokens to minimize the window of vulnerability.
- Regulatory Compliance: Compliance requirements, such as GDPR (General Data Protection Regulation) in the European Union, may mandate specific data retention and access control practices, including token expiration policies.
- User Experience: Longer-lived tokens provide a smoother user experience by reducing the frequency of token renewal or reauthentication. However, this convenience must be balanced with security considerations.
- Token Revocation Mechanisms: The presence of token revocation mechanisms, such as blacklisting or token invalidation, affects the acceptable validity period. Shorter-lived tokens may be preferable when efficient revocation mechanisms are in place.
Best Practices for Setting Validity Period
When setting the validity period of JWT tokens, consider the following best practices:
- Short-Lived Tokens: Prefer shorter-lived tokens to minimize the risk of unauthorized access in case of token leakage or compromise. Typical expiration times range from minutes to hours, depending on the application's security requirements.
- Refresh Tokens: Combine short-lived access tokens with longer-lived refresh tokens. Refresh tokens can be used to obtain new access tokens without requiring the user to reauthenticate, mitigating the impact of short expiration times on user experience.
- Dynamic Expiration: Implement dynamic expiration policies based on user activity, session context, or access patterns. Extend the expiration time for active sessions while revoking inactive or suspicious tokens promptly.
- Token Rotation: Periodically rotate JWT tokens and refresh tokens to limit their lifespan and reduce the likelihood of successful token-based attacks.
Conclusion
The validity period of JWT tokens plays a critical role in ensuring the security, compliance, and usability of authentication mechanisms in web applications and APIs. By setting appropriate expiration times and adopting best practices for token management, developers can strike a balance between security requirements and user experience, thereby enhancing the overall resilience and trustworthiness of their systems.
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read