
Authentication is one of the most important parts of modern web development. Whether you are building a social media application, an e-commerce website, or a REST API, you need a reliable way to verify users before allowing them to access protected resources.
One popular approach is JWT authentication.
JWT is widely used in applications built with React, Next.js, Node.js, Express.js, and other technologies. It allows a server to issue a token after a user successfully authenticates. The client can then present that token when making requests to protected endpoints.
But what exactly is JWT authentication, how does it work, and how can you implement it in Node.js?
In this guide, we'll explain JWT authentication step by step, explore its advantages and limitations, and build a simple example using Express.js.
What Is JWT Authentication?
JWT stands for JSON Web Token. It is a compact format for representing claims that can be transferred between parties.
A JWT is commonly used in authentication systems to represent information about an authenticated user and to help a server determine whether a request is authorized.
For example, when a user logs in to an application with an email address and password, the server can verify those credentials and issue an access token.
The client then sends the token with subsequent requests to protected API endpoints.
If the token is valid and the user has the required permissions, the server can process the request.
JWTs are standardized in RFC 7519 and are commonly used in web applications, mobile apps, and API-based systems.
What Does a JWT Look Like?
A typical signed JWT contains three parts separated by periods:
xxxxx.yyyyy.zzzzzThese parts are:
Header
Payload
Signature
A real JWT might look like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NTAxMjM0NSIsInJvbGUiOiJ1c2VyIn0.signatureThis is an illustrative example, not a token you should use for authentication.
Let's understand each part.
1. Header
The header describes the token type and the signing algorithm.
For example:
{
"alg": "HS256",
"typ": "JWT"
}Here, HS256 identifies the HMAC SHA-256 signing algorithm.
2. Payload
The payload contains claims, which are statements about the subject or other information associated with the token.
For example:
{
"sub": "user123",
"role": "user",
"iat": 1790000000,
"exp": 1790003600
}Some common claims include:
sub: The subject, often the user's identifier.iat: The time the token was issued.exp: The time the token expires.iss: The token issuer.aud: The intended audience.
Applications can also include custom claims, such as a user ID or role.
Important: A typical signed JWT is not encrypted. Anyone who obtains it can generally decode its header and payload. Never store passwords, private keys, or other secrets inside a JWT payload.
3. Signature
The signature helps the receiving application verify that the token has not been modified and was signed using the expected key or secret.
For an HMAC-signed token, the signature is calculated using the encoded header, encoded payload, and a secret key.
If someone changes the payload without being able to produce a valid signature, verification will fail.
However, a valid signature does not automatically mean the user should be allowed to perform every action. The server must still check expiration, issuer, audience where applicable, and the user's permissions.
How Does JWT Authentication Work?
JWT authentication usually follows a simple sequence.
Imagine that you are building a MERN stack application with React on the frontend and Node.js on the backend.
The authentication flow looks like this:
Step 1: The user logs in.
The user enters their email address and password in the login form.
Step 2: The frontend sends credentials to the backend.
React sends a request to the login API.
POST /api/auth/login
Content-Type: application/jsonThe request body contains the user's credentials.
Step 3: The backend verifies the credentials.
Node.js checks whether the user exists and compares the submitted password with the stored password hash.
Step 4: The server generates a JWT.
If authentication succeeds, the backend signs an access token containing the necessary claims.
Step 5: The client receives the token.
Depending on the application's design, the token may be delivered in a response body or set in a secure cookie.
Step 6: The client accesses a protected endpoint.
For bearer-token authentication, the client sends the access token in the HTTP Authorization header.
Authorization: Bearer <access_token>Step 7: The backend verifies the token.
The backend checks the token's signature and relevant claims.
If the token is valid and the user has permission to access the resource, the server processes the request.
This process allows the application to protect API endpoints without asking users to enter their passwords for every request.
JWT Authentication vs. Session-Based Authentication
JWT authentication and session-based authentication are two common approaches to managing authenticated users.
They work differently.
Session-Based Authentication
In a traditional session-based system, the server creates a session after a successful login.
The browser receives a session identifier, usually through a cookie. The server uses that identifier to find the corresponding session data.
The session can contain information about the authenticated user and other authentication state.
JWT-Based Authentication
In a JWT-based system, the server issues a token containing signed claims.
The client sends the token with subsequent requests, and the server verifies it before processing protected operations.
Depending on the architecture, the server may also maintain revocation records or other state.
Comparison Table
Feature | JWT Authentication | Session-Based Authentication |
|---|---|---|
Authentication data | Signed token claims | Server-side session data |
Client typically stores | Token or secure cookie | Session ID in a cookie |
Server-side storage | May not be needed for access-token validation | Usually required for session lookup |
Revocation | Can be more complex without server-side state | Often straightforward by invalidating the session |
Scalability | Can work well across distributed APIs | Can scale with shared session storage |
Data visibility | Signed JWT payload is usually readable | Session data normally stays on the server |
Best use case | Distributed APIs and token-based integrations | Traditional web applications and applications needing centralized session control |
Which one is better?
Neither approach is universally better.
JWTs can be useful when multiple services need to verify access tokens. Sessions can be easier to revoke and manage centrally.
The right choice depends on your application, security requirements, infrastructure, and how you want to handle logout and revocation.
How to Implement JWT Authentication in Node.js and Express.js
Let's build a basic JWT authentication example using Node.js and Express.js.
This example demonstrates token creation and verification. It is a learning example, not a complete production authentication system.
We'll use:
Node.js for the backend runtime.
Express.js for API routes.
jsonwebtokento sign and verify JWTs.bcryptjsto hash passwords.
Step 1: Create a Project
Create a new project directory:
mkdir jwt-auth-demo
cd jwt-auth-demo
npm init -yInstall the required dependencies:
npm install express jsonwebtoken bcryptjs dotenvStep 2: Configure Environment Variables
Create a .env file:
PORT=5000
JWT_SECRET=replace_with_a_long_random_secretGenerate a strong, random secret for your local environment.
For example, you can generate one with Node.js:
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"Copy the generated value into your .env file.
Never commit your real JWT secret to GitHub or expose it in frontend code.
For production deployments, use a secure secrets manager or the environment configuration provided by your hosting platform.
Step 3: Create the Express Server
Create a file named server.js:
require("dotenv").config();
const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const app = express();
app.use(express.json());
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) {
throw new Error("JWT_SECRET is required");
}
// Demo-only in-memory user store.
// Replace this with a database in a real application.
const users = [];
// Register a user.
app.post("/api/auth/register", async (req, res) => {
try {
const { email, password } = req.body;
if (
typeof email !== "string" ||
typeof password !== "string" ||
!email.trim() ||
password.length < 8
) {
return res.status(400).json({
message:
"Provide a valid email and a password with at least 8 characters",
});
}
const normalizedEmail = email.trim().toLowerCase();
const existingUser = users.find(
(user) => user.email === normalizedEmail
);
if (existingUser) {
return res.status(409).json({
message: "User already exists",
});
}
const hashedPassword = await bcrypt.hash(password, 12);
const user = {
id: String(users.length + 1),
email: normalizedEmail,
password: hashedPassword,
role: "user",
};
users.push(user);
return res.status(201).json({
message: "User registered successfully",
});
} catch (error) {
return res.status(500).json({
message: "Internal server error",
});
}
});
// Log in and create an access token.
app.post("/api/auth/login", async (req, res) => {
try {
const { email, password } = req.body;
if (
typeof email !== "string" ||
typeof password !== "string"
) {
return res.status(400).json({
message: "Email and password are required",
});
}
const normalizedEmail = email.trim().toLowerCase();
const user = users.find(
(item) => item.email === normalizedEmail
);
if (
!user ||
!(await bcrypt.compare(password, user.password))
) {
return res.status(401).json({
message: "Invalid email or password",
});
}
const accessToken = jwt.sign(
{
role: user.role,
},
JWT_SECRET,
{
subject: user.id,
expiresIn: "15m",
algorithm: "HS256",
}
);
return res.json({
message: "Login successful",
accessToken,
});
} catch (error) {
return res.status(500).json({
message: "Internal server error",
});
}
});
// Authentication middleware.
function authenticateToken(req, res, next) {
const authorization = req.headers.authorization;
if (!authorization || !authorization.startsWith("Bearer ")) {
return res.status(401).json({
message: "Access token is required",
});
}
const token = authorization.slice(7);
try {
const payload = jwt.verify(token, JWT_SECRET, {
algorithms: ["HS256"],
});
req.user = {
id: payload.sub,
role: payload.role,
};
next();
} catch (error) {
return res.status(401).json({
message: "Invalid or expired access token",
});
}
}
// Protected route.
app.get("/api/profile", authenticateToken, (req, res) => {
return res.json({
message: "Protected profile accessed successfully",
user: req.user,
});
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});Step 4: Start the Server
Run:
node server.jsThe server should start on port 5000 unless you configured another port.
The example keeps users in an in-memory array, so registered users disappear when the server restarts. A real application should use a persistent database and should not rely on an in-memory user store.
Step 5: Register a User
Send a POST request to:
http://localhost:5000/api/auth/registerRequest body:
{
"email": "developer@example.com",
"password": "StrongPassword123!"
}If registration succeeds, the server returns a success message.
For a production system, add stronger validation, email verification where appropriate, rate limiting, and appropriate account-security controls.
Step 6: Log In
Send a POST request to:
http://localhost:5000/api/auth/loginRequest body:
{
"email": "developer@example.com",
"password": "StrongPassword123!"
}The server verifies the password and returns an access token.
The response will look similar to this:
{
"message": "Login successful",
"accessToken": "<signed_jwt>"
}The token value will be generated dynamically.
Step 7: Access a Protected Route
Copy the access token and send a GET request to:
http://localhost:5000/api/profileAdd this HTTP header:
Authorization: Bearer <your_access_token>If the token is valid, the API returns the user's ID and role.
If the token is missing, invalid, or expired, the API returns an HTTP 401 response.
This is the core idea behind JWT authentication: the client presents a token, and the backend verifies it before allowing access to a protected endpoint.
What Is JWT Authentication Middleware?
Authentication middleware is a function that runs before a protected route handler.
Its job is to check whether a request includes valid authentication credentials.
In Express.js, middleware commonly performs these tasks:
Reads the token from the request.
Verifies its signature.
Checks whether the token has expired.
Extracts relevant claims.
Attaches the authenticated user's identity to the request.
Passes control to the next middleware or route handler.
For example:
app.get("/api/orders", authenticateToken, (req, res) => {
res.json({
message: "Authenticated user can access this route",
userId: req.user.id,
});
});The authenticateToken middleware runs before the route handler.
However, authentication and authorization are different.
Authentication determines who the user is. Authorization determines what that user is allowed to do.
For example, an administrator-only route should check the user's permissions after authentication.
function requireAdmin(req, res, next) {
if (req.user.role !== "admin") {
return res.status(403).json({
message: "Access forbidden",
});
}
next();
}
app.delete(
"/api/admin/users/:id",
authenticateToken,
requireAdmin,
(req, res) => {
res.json({
message: "Admin operation authorized",
});
}
);In a real application, administrative permissions should come from trusted server-side data or claims that the server issues and validates appropriately. Never trust a role sent directly by the client.
What Are Access Tokens and Refresh Tokens?
Many applications use two types of tokens to balance security and convenience.
Access Token
An access token is sent with requests to protected resources.
It typically has a short lifetime, such as 5–15 minutes, depending on the application's risk profile and requirements.
If an access token is stolen, its short expiration can limit the period in which it remains usable. However, the token can still be abused until it expires or is otherwise invalidated.
Refresh Token
A refresh token is used to obtain a new access token without requiring the user to enter their password again.
Refresh tokens generally have a longer lifetime and must be protected carefully.
A secure refresh-token implementation should consider:
Secure storage.
Expiration.
Token rotation.
Revocation.
Reuse detection.
Logout behavior.
For browser-based applications, a common design is to keep refresh tokens in cookies configured with HttpOnly, Secure, and an appropriate SameSite policy.
If cookies are used for authentication, the application must also consider cross-site request forgery (CSRF) protections.
How the Refresh Flow Works
The user logs in.
The server issues an access token and a refresh token.
The client uses the access token to call protected APIs.
When the access token expires, the client sends the refresh token to the refresh endpoint.
The server validates the refresh token.
If valid, the server issues a new access token and may rotate the refresh token.
If the refresh token is invalid, expired, revoked, or reused unexpectedly, the server rejects the refresh request and may require the user to log in again.
Refresh-token handling is more complicated than simply creating another JWT. It should be designed around the application's security requirements.
Where Should You Store a JWT?
Token storage is an important security decision.
Different approaches have different risks.
1. Local Storage
Browser local storage is convenient because JavaScript can read the stored token.
However, this also means a successful cross-site scripting (XSS) attack may allow malicious JavaScript to steal it.
For sensitive applications, storing long-lived authentication tokens in local storage can create significant risk.
2. Session Storage
Session storage is scoped to a browser tab's session, but JavaScript can still access it.
Consequently, an XSS vulnerability may expose tokens stored there as well.
3. HttpOnly Cookies
Cookies configured with the HttpOnly attribute cannot be read directly by JavaScript.
When combined with Secure, an appropriate SameSite setting, sensible expiration, and CSRF protections where necessary, cookies can be a good choice for browser-based authentication.
Cookies are not automatically secure simply because they are cookies. Their configuration and the surrounding application architecture matter.
Which Storage Option Is Best?
There is no single solution for every application.
For many first-party browser applications, secure cookies are a strong option, particularly for refresh tokens.
For mobile applications, use appropriate platform-provided secure storage.
Choose the storage strategy based on your threat model, client type, and authentication architecture. Avoid exposing long-lived bearer tokens unnecessarily.
Common JWT Authentication Mistakes
JWT authentication can be implemented incorrectly if developers overlook important security details.
Here are some common mistakes to avoid.
1. Using a Weak Secret
A weak signing secret may make certain JWT signing schemes vulnerable to attacks.
Use a cryptographically strong secret generated with a secure random generator.
Keep it private and rotate it according to an appropriate operational plan.
2. Storing Sensitive Information in the Payload
A signed JWT is not necessarily encrypted.
Avoid putting passwords, payment details, private keys, or other sensitive information in its payload.
Only include claims that the receiving service actually needs.
3. Giving Access Tokens Excessively Long Lifetimes
Long-lived access tokens can increase the damage caused by token theft.
Use an expiration appropriate to your application's security needs, and implement a strategy for revoking or replacing credentials when necessary.
4. Skipping Signature Verification
Never authorize a request just because the token looks like a JWT.
Use a trusted library to verify the signature and validate relevant claims.
Avoid unsafe configurations that accept unexpected signing algorithms.
5. Ignoring Authorization
A valid token does not automatically grant access to every resource.
The backend must verify that the authenticated user has permission to perform the requested action.
6. Forgetting Logout and Revocation
A stateless access token may remain usable until expiration unless the application has a revocation mechanism or another way to invalidate it.
A logout operation should clear client-side credentials and invalidate or revoke refresh tokens where applicable.
For higher-risk applications, consider whether access-token revocation or a server-side session mechanism is necessary.
7. Not Using HTTPS
Tokens sent over unencrypted HTTP can be exposed to attackers who can observe or modify network traffic.
Use HTTPS for authentication endpoints and protected APIs in production.
Advantages of JWT Authentication
JWT authentication offers several benefits when used appropriately.
1. Compact Format
JWTs are relatively compact, making them convenient to transmit in HTTP headers or cookies.
2. Useful for Distributed Systems
Multiple services can verify a signed token when they share the appropriate verification key and agree on the token's issuer, audience, and claims.
With asymmetric signing, services can verify tokens using a public key without possessing the private signing key.
3. Reduced Need for Session Lookups
A service can validate an access token without looking up a server-side session on every request, provided that the architecture does not require additional state or revocation checks.
4. Flexible Claims
JWTs can carry useful claims, such as a subject identifier, issuer, audience, and expiration.
These claims help services make authentication and authorization decisions.
Disadvantages of JWT Authentication
JWT authentication also has limitations.
1. Revocation Can Be Difficult
A self-contained access token may remain valid until it expires.
Immediate revocation can require a denylist, token-version checks, short expiration times, or another server-side mechanism.
2. Tokens Can Be Stolen
If an attacker obtains a valid bearer token, they may be able to use it until it expires or is invalidated.
Secure storage, HTTPS, XSS prevention, and careful token handling are therefore essential.
3. Tokens Can Become Large
Adding unnecessary claims increases token size and the amount of data sent with requests.
Keep the payload small and avoid including information that can be retrieved securely from the server when needed.
4. JWT Is Not a Complete Authentication System
JWT provides a token format and related security mechanisms. It does not automatically implement secure registration, password resets, multifactor authentication, user management, authorization, or account recovery.
Those parts must be designed and implemented separately.
Frequently Asked Questions (FAQs)
1. What does JWT stand for?
JWT stands for JSON Web Token. It is a compact format for representing claims that can be transmitted between parties.
2. Is JWT authentication secure?
JWT authentication can be secure when implemented correctly. Use strong signing keys, validate tokens properly, set appropriate expiration times, protect token storage, use HTTPS, and implement authorization checks.
A JWT alone does not guarantee application security.
3. Is JWT better than sessions?
Neither JWTs nor sessions are always better. JWTs can be useful for distributed APIs, while sessions can offer simpler centralized control and revocation.
The right choice depends on the application's requirements.
4. Can JWT be used with React and Node.js?
Yes. React can send authentication requests and include access tokens in API requests, while Node.js can issue and verify JWTs.
For browser-based applications, carefully consider whether cookies or another token-storage strategy is appropriate.
5. Does JWT encrypt user data?
A typical signed JWT does not encrypt its payload. The payload is usually encoded, not secret.
Anyone who obtains the token can generally decode its claims. Use encryption only when it is specifically required and correctly implemented, and never rely on a signed JWT to hide sensitive information.
6. What happens when a JWT expires?
The server should reject an expired access token.
If the application supports refresh tokens, the client may request a new access token. Otherwise, the user may need to authenticate again.
7. Can JWT be used without a database?
JWT verification itself does not necessarily require a database lookup.
However, most applications still need a database for user accounts, password hashes, roles, and other persistent information. Some systems also use a database or cache for refresh-token records and revocation checks.
8. How long should a JWT access token last?
There is no universal expiration time. Some applications use lifetimes of 5–15 minutes, while others choose different values based on risk, usability, and infrastructure requirements.
Shorter lifetimes can reduce the period of exposure after token theft but may require more frequent refresh operations.
9. What is the difference between a JWT and a bearer token?
A JWT is a token format. A bearer token is a credential that grants access to whoever possesses it.
A JWT is often used as a bearer token in an HTTP Authorization header, but not every bearer token is a JWT.
10. Should I use JWT in every Node.js project?
No. JWT is useful in many API-based applications, but session-based authentication or an established identity provider may be a better fit for some projects.
Choose the approach that meets your security, usability, and operational requirements.
Conclusion
JWT authentication is a widely used approach for protecting APIs and managing authenticated access in modern applications.
It works by allowing a server to issue a signed token after successful authentication. The client then presents that token when accessing protected endpoints, and the backend verifies it before processing requests.
For Node.js developers, understanding JWT authentication is especially useful when building REST APIs, React applications, Next.js projects, and distributed services.
However, JWT is only one component of a secure authentication system. Proper password hashing, token storage, expiration, revocation, authorization, and HTTPS are all important.
Start by understanding how access tokens work, practice implementing authentication middleware, and then learn how refresh tokens and secure cookies fit into a complete authentication flow.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


