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
How to Validate JSON in PHP ?
Validating JSON in PHP refers to the process of checking whether a JSON string is properly formatted and valid according to JSON standards. In PHP, the json_decode() function is used to parse JSON, and validation can be checked using json_last_error() for errors. It is a PHP built-in function that i
3 min read
How To Check Uuid Validity In Python?
UUID (Universally Unique Identifier) is a 128-bit label used for information in computer systems. UUIDs are widely used in various applications and systems to uniquely identify information without requiring a central authority to manage the identifiers. This article will guide you through checking t
3 min read
How to Get Session Token in AWS?
A session token is a popular concept that is used in AWS for giving access to some user or person for a limited amount of time, in this the user gets to access the AWS resources but only for a limited amount of time only. The purpose of the session token is to have more security in the AWS system so
6 min read
How to Validate JSON Schema ?
Validating JSON schema ensures that the structure and data types within a JSON document adhere to a predefined schema. This process is crucial for ensuring data consistency and integrity in applications where JSON data is exchanged. ApproachImport the Ajv Library, a popular JSON Schema validator for
2 min read
How to Validate Data using joi Module in Node.js ?
Joi module is a popular module for data validation. This module validates the data based on schemas. There are various functions like optional(), required(), min(), max(), etc which make it easy to use and a user-friendly module for validating the data. Introduction to joi It's easy to get started a
3 min read
How to Generate JWT Tokens using FastAPI in Python
In this article, we will see how to create and validate a JWT in the FastAPI framework. This is a very basic example of how to create and validate the tokens, this is just for reference, and using this approach one can easily create JWT according to the need and use it accordingly while validation.
4 min read
How To Get The API Token For Jenkins ?
Jenkins is an open-source automation tool that automates the build, test, and deployment stages of software. In this guide, I will first discuss what Jenkins is. Then I would discuss why to generate API tokens in Jenkins. After this, I will guide you through the different steps to generate an API to
4 min read
What is a Security Token?
Let us imagine that we are been provided with just an ID and password to access any of our logins and if any stranger has seen it then it is obvious that they can see our data. This means our privacy has been compromised so we needed a way to overcome this issue so a security token was introduced in
12 min read
How to Create and View Access Tokens in NPM ?
Access tokens are important components in the npm ecosystem, used as authentication mechanisms for users to interact with npm registries securely. They grant permissions for actions such as publishing packages, accessing private packages, or managing user accounts. In this article, we will see how t
2 min read
How to Send ERC20 Token with Web3.js?
Sending ERC20 tokens is a common task in the world of Ethereum and decentralized applications. ERC20 tokens are a type of digital asset that lives on the Ethereum blockchain and follows a specific set of rules. The article focuses on discussing how to send ERC20 tokens using Web3.js, a popular JavaS
6 min read