Most beginner auth tutorials hand you a login route, a secret string, and a token generator, then stop. You get something that works in Postman, but you do not understand why the middleware exists, why the token has three parts, or what happens when it expires.
This walkthrough builds a minimal JWT authentication flow in Node.js and explains each piece as it appears. By the end, you will have a login route, a protected route, and a clear mental model of how the token travels between them.
What a JWT Actually Contains
A JSON Web Token is three Base64Url-encoded strings joined by dots: a header, a payload, and a signature . The header names the signing algorithm. The payload carries claims — pieces of information about the user, like an ID or a role. The signature is what makes the token tamper-evident.
The signature is created by combining the header, the payload, and a secret key using the algorithm named in the header. If anyone changes the payload — say, swapping a user ID for an admin ID — the signature no longer matches, and verification fails .
This is why you never put secrets in the payload. Anyone holding the token can decode the payload and read it. The signature prevents modification, not inspection.
Set Up the Project
You need a directory, a package.json, and two packages: Express for the server and jsonwebtoken for signing and verifying [citation:1].
mkdir jwt-auth-demo
cd jwt-auth-demo
npm init -y
npm install express jsonwebtoken
As of late 2026, the current jsonwebtoken release is 9.0.3, and Node 24.x is the Active LTS line [citation:6][citation:11]. The code below works on Node 20 and later without changes.
Build the Server Skeleton
Create index.js and start with the minimum: Express, JSON body parsing, and a port.
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET || 'dev-only-secret-change-me';
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
The fallback secret exists only so the demo runs without a .env file. In anything real, read it from an environment variable and never commit it. We covered the mechanics of .env files in a separate post, but the short version is: a secret in your source code is a secret you have already leaked.
Write the Login Route
The login route checks credentials and, on success, signs a token. For a beginner walkthrough, hardcoded credentials keep the focus on the token flow. Replace them with a database lookup when you move past the demo [citation:1].
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username !== 'demo' || password !== 'password123') {
return res.status(401).json({ message: 'Invalid credentials' });
}
const token = jwt.sign(
{ username, role: 'user' },
JWT_SECRET,
{ expiresIn: '1h' }
);
res.json({ token });
});
jwt.sign() takes the payload, the secret, and options. expiresIn sets the exp claim, which is the expiration timestamp. One hour is a reasonable starting point for a demo; production systems often use shorter access tokens paired with refresh tokens [citation:9].
Write the Middleware That Protects Routes
This is the piece most tutorials rush. A middleware function runs before your route handler, inspects the request, and either calls next() to continue or ends the request with an error.
function authenticateToken(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ message: 'Missing or malformed token' });
}
const token = authHeader.split(' ')[1];
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
return res.status(401).json({ message: 'Invalid or expired token' });
}
}
Three things happen here. The middleware checks for a Bearer prefix in the Authorization header. It verifies the signature and expiration using jwt.verify(). If verification succeeds, it attaches the decoded payload to req.user and calls next() so the route handler can run [citation:9].
If you are using Express 5, keep the return before res.status(...).json(...) and call next() explicitly on success. Express 5's type expectations are stricter about middleware return values, and this pattern avoids the common mismatch where a middleware returns a Response object instead of void [citation:8].
Add a Protected Route
Attach the middleware to any route that needs a valid token. The route handler can then trust req.user without re-checking the token.
app.get('/profile', authenticateToken, (req, res) => {
res.json({
message: 'You reached a protected route',
user: req.user
});
});
The order matters: authenticateToken runs first, and only calls next() when the token is valid. If it is missing, malformed, or expired, the handler never runs.
Test the Flow
Start the server with node index.js. Use Postman, curl, or any HTTP client to run two requests.
Step 1: Log in. Send a POST to /login with a JSON body containing the demo credentials. Copy the token value from the response.
Step 2: Call the protected route. Send a GET to /profile with a header named Authorization and a value of Bearer, a space, then the token. You should get back a JSON object with the message and the decoded user [citation:1].
Try the same request without the header, or with a token you have edited by one character. You should get a 401. That difference — between a valid signature and an invalid one — is the entire point of the token.
Common Beginner Mistakes
- Storing the secret in the code. Move it to an environment variable before this touches a repository.
- Setting
expiresInto something huge. A token that never expires is a password that never changes. Use a reasonable window and plan for refresh. - Putting sensitive data in the payload. The payload is readable by anyone with the token. It is a claim, not a vault.
- Forgetting the
Bearerprefix. The middleware expectsBearer <token>, not the raw token alone. - Trusting
req.userwithout verifying. The middleware is what makesreq.usertrustworthy. Never set it from a request body.
Frequently Asked Questions
Where should I store the token on the client?
The safe default is an HTTP-only cookie, because JavaScript cannot read it and cross-site scripting cannot steal it directly. Storing it in localStorage is common in tutorials but exposes the token to any script running on the page. If you use localStorage, understand that trade-off.
What happens when the token expires?
jwt.verify() throws an error when the exp claim is in the past. Your middleware catches it and returns a 401. The client then needs a way to get a new token — either by logging in again or by using a refresh token flow, which is a separate topic.
Can I invalidate a JWT before it expires?
Not with the token alone. JWTs are stateless by design: the server does not keep a session record to delete. To revoke a token early, you need a server-side blocklist or a short expiration window. This is the trade-off for not storing sessions.
Is jsonwebtoken still maintained?
Yes. Version 9.0.3 is the current release, and the package remains the standard choice for JWT signing and verification in Node.js [citation:6].
Do I need TypeScript for this?
No. The walkthrough uses plain JavaScript. If you add TypeScript later, Express 5's stricter middleware types will push you toward the next()-based error pattern shown above, which is a good habit regardless [citation:8].
The Bottom Line
JWT authentication is three moving parts: a route that signs a token, a middleware that verifies it, and routes that sit behind the middleware. The token itself is just a signed claim about who the user is. Understand the signature, the expiration, and the Bearer header convention, and the rest of the ecosystem — refresh tokens, cookies, role checks — becomes much easier to reason about.
.png)