A JSON Web Token (JWT) is a standard used to securely transmit information between a client (like a frontend application) and a server (the backend). It is commonly used to verify users’ identities, authenticate them, and ensure safe communication between the two. JWTs are mainly used in web apps and APIs to protect against unauthorized access.
The data in a JWT, such as user details, is stored in a simple JSON format. To keep the data safe, the token is signed cryptographically, making sure that no one can alter it. The signing can be done using these cryptographic methods:
- HMAC (Hash-based Message Authentication Code)
- RSA or ECDSA (Asymmetric cryptographic algorithms)
JWTs are primarily used for authentication and secure data exchange in web applications and APIs.
How JWT token Works?
- User Logs In: The client (browser) sends login credentials to the server.
- Server Generates JWT: If credentials are valid, the server creates a JWT containing user data and signs it with a secret key.
- Token Sent to Client: The JWT is sent back to the client and stored (usually in localStorage or a cookie).
- Client Sends Token in Requests: For protected routes, the client includes the JWT in the Authorization header (Bearer Token).
- Server Verifies and Responds: The server verifies the token, extracts user info, and processes the request if valid.
What are Tokens and Why Are They Needed?
Tokens are used to securely transmit sensitive information between the client and the server. Instead of sending plain data (e.g., user info) that could be tampered with, tokens provide a secure method of validation. JWTs are widely adopted because they are tamper-proof, ensuring that data remains unaltered during transmission.
JWT Structure

Structure of a JWT
A JWT consists of three parts, separated by dots (.)
Header. Payload. Signature
- Header: Contains metadata about the token, such as the algorithm used for signing.
- Payload: Stores the claims, i.e., data being transmitted.
- Signature: Ensures the token’s integrity and authenticity.
1. Header
The header contains metadata about the token, including the signing algorithm and token type here metadata means data about data.
{
"alg": "HS256",
"typ": "JWT"
}
- alg: Algorithm used for signing (e.g., HS256, RS256).
- typ: Token type, always “JWT”.
Base64Url Encoded Header
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
2. Payload
The payload contains the information about the user also called as a claim and some additional information including the timestamp at which it was issued and the expiry time of the token.
{
"userId": 123,
"role": "admin",
"exp": 1672531199
}
Common claim types:
- iss (Issuer): Identifies who issued the token.
- sub (Subject): Represents the user or entity the token is about.
- aud (Audience): Specifies the intended recipient.
- exp (Expiration): Defines when the token expires.
- iat (Issued At): Timestamp when the token was created.
- nbf (Not Before): Specifies when the token becomes valid.
Base64Url Encoded Payload
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNzA4MzQ1MTIzLCJleHAiOjE3MDgzNTUxMjN9
3. Signature
The signature ensures token integrity and is generated using the header, payload, and a secret key. In this example we will use HS256 algorithm to implement the Signature part
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
Example Signature:
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
4. Final JWT token
After all these steps the final JWT token is generated by joining the Header, Payload and Signature via a dot. It looks like as it is shown below.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNzA4MzQ1MTIzLCJleHAiOjE3MDgzNTUxMjN9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Security Considerations
- Use HTTPS: Prevent man-in-the-middle attacks by transmitting JWTs over HTTPS.
- Set Expiration Time: Prevent long-lived tokens that can be exploited.
- Use Secure Storage: Store JWTs securely (e.g., HttpOnly cookies instead of local storage).
- Verify Signature: Always validate the token’s signature before trusting its content.
Implementing JWT in a web application
1. Code to create a JSON web token
This code generates a JWT (JSON Web Token) using the jsonwebtoken library in Node.js. The token contains user data and is signed with a secret key for security.
Command to install jsonwebtoken library in NodeJS
npm install jsonwebtoken
JavaScript
const jwt = require('jsonwebtoken');
const secretKey = 'abcde12345';
const token = jwt.sign({
id: 1,
username: 'GFG'
}, secretKey, { expiresIn: '1h' });
console.log(token);
Output

Code to create a JSON web token
- Importing JWT Library: The jsonwebtoken module is required to create and verify tokens.
- Defining Secret Key: A secret key (abcde12345) is used to sign the token securely.
- Creating JWT: The jwt.sign() method generates a token with user details (id, username) and an expiration time of 1 hour.
- Logging the Token: The generated JWT is printed to the console for use in authentication.
2. Code to verify a JSON web token
This code verifies a JWT using the jsonwebtoken library in Node.js. It checks if the token is valid and extracts the payload if authentication succeeds.
JavaScript
jwt.verify(token, 'abcde12345', (err, decoded) => {
if (err) {
console.log('Token is invalid');
} else {
console.log('Decoded Token:', decoded);
}
});
Output

Code to verify a JSON web token
- Verifying the Token: The jwt.verify() method checks if the provided token is valid using the secret key.
- Handling Errors: If verification fails, an error (err) occurs, and “Token is invalid” is logged.
- Decoding Token Data: If valid, the decoded object contains the original user details.
- Logging the Decoded Data: The decoded payload is printed to the console, showing user details from the token.
Common Issues During Development with JWT
JWT errors often arise from mismatched details or token problems:
- JWT Rejected : This means the server couldn’t verify the token. It might happen because:
- The JWT has expired: The token is no longer valid because it passed its expiration time.
- The signature doesn’t match: The token might have been tampered with, or the signing keys have changed.
- Other claims don’t match: For example, if the token was created for one app but sent to another, the app will reject it because it doesn’t match the expected details.
- JWT Token Doesn’t Support the Required Scope: A JWT contains permissions (called “scopes”) that define what actions the user has agreed to. If the app requires more permissions than the token provides, it will be rejected. For instance, if the app needs permission to modify data, but the token only allows reading data, it won’t work.
- JWT Decode Failed : This happens when the token isn’t in the expected format. For example, the client might expect the JWT to be base64 encoded, but if the server didn’t encode it that way, the client won’t be able to read it properly.
Advantages of using JSON Web Token
JWTs are widely used for authentication and authorization due to their numerous advantages:
- Stateless Authentication: No need to store user sessions on the server; JWT contains all necessary data.
- Compact & Fast: Being small in size, JWT is efficiently transmitted in HTTP headers, making it ideal for APIs.
- Secure & Tamper-Proof: JWTs are signed using a secret key or public/private key pair, ensuring integrity.
- Cross-Platform Support: Can be used with any technology (JavaScript, Python, Java, etc.) for authentication.
- Built-in Expiry: Tokens can have an expiration time (expiresIn), reducing the risk of long-term access misuse.
Conclusion
JSON Web Tokens (JWT) provide a secure, fast, and stateless way to handle authentication. They are widely used in APIs, web apps, and mobile apps due to their compact size, cross-platform support, and built-in security features. By leveraging JWT, developers can ensure safe and efficient user authentication without storing sessions on the server.
Similar Reads
How to use JSON web tokens with Node.js ?
JSON Web Token (JWT) is an Internet Standard that is used for exchanging data between two parties in a secure manner. It can't be easily hacked as it creates a digital signature with the secret key along with the HMAC algorithm). JWT Structure: JSON Web Tokens consist of three parts separated by do
4 min read
How Long is a JWT Token Valid ?
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 th
6 min read
Web APIs Tutorial
What is Web API?Web API is the API provided by the web browser and can be used directly to fetch any kind of data of that device or any other details according to the used API. The web includes a variety of APIs that can be used to add more functions to the web. Basically web API provides many more
5 min read
JWT Authentication With Refresh Tokens
Authentication is a critical part of web applications. Using JWT (JSON Web Tokens) for authentication is common, but adding refresh tokens provides an added layer of security and convenience. In this article, weâll discuss how to implement JWT authentication with refresh tokens. JWT (JSON Web Token)
5 min read
What is Google Web Toolkit(GWT)?
Google Web Toolkit (GWT) is an open-source web application framework developed by Google. Â It is a Java-based framework that allows developers to write web applications in Java and compile the code to highly optimized JavaScript, HTML, and CSS. The framework was first released in 2006 and has since
10 min read
Web Storage API
Web API Storage facilitates the feature of storing data within the browser on the client side. It is also referred to as web storage. It uses a key-value pair format to store the data. Table of Content Web Storage API Concepts and UsageWeb Storage API InterfacesExamples Showing of Web Storage APIWeb
3 min read
What is a Webhook and How to Use it?
Webhooks allow interaction between web-based applications through the use of custom callbacks. The use of webhooks allows web applications to automatically communicate with other web-apps. Unlike traditional systems where one system (subject) keeps polling another system (observer) for some data, We
6 min read
Components of Web Services
Web services are software systems designed to enable machine-to-machine interaction over the internet. They are used to share data and functionality between different applications and systems. Here are some of the different types of web services and their importance, which are described below: SOAP
5 min read
Node.js http2session.type Method
The http2session.type is an inbuilt application programming interface of class http2session within http2 module which is used to return the type of session instance used in the peer process. Syntax: const http2session.type Parameters: This method does not takes any argument as a parameter. Return Va
3 min read
Latest Web API Technologies
A Web API (Application Programming Interface) is a set of protocols and tools for building software applications. Specifically, a web API is a type of API that is accessed through the internet, typically using HTTP requests. Web APIs allow developers to interact with remote systems or services over
6 min read