JWT Authentication Tutorial: Build a Secure Login System in Node.js
Dec 03, 2026 7 Min Read 17 Views
(Last Updated)
Every REST API that handles user data has to answer one question on each request: who is calling, and are they allowed in? HTTP is stateless, so the server does not remember a login between requests. Token-based authentication fixes this by handing the client a signed token at login and verifying it on every call after that.
JSON Web Tokens (JWT) are the most widely used way to do this in Node.js APIs. This JWT authentication tutorial walks you through building a secure login system with Express.js, MongoDB, bcrypt and the jsonwebtoken library. You will register users, hash passwords, issue access and refresh tokens, protect routes with middleware, and test every case in Postman.
Table of contents
- TL;DR
- What Is JWT Authentication?
- Header
- Payload
- Signature
- How JWT Authentication Works in a REST API
- Prerequisites and Project Setup
- Build JWT Authentication in Node.js
- Step 1: Create the Express server and connect MongoDB
- Step 2: Create the user model and hash passwords
- Step 3: Implement registration, login and token generation
- Step 4: Create the authentication middleware and protect routes
- JWT Access Token vs Refresh Token
- Test the JWT Authentication System Using Postman
- Register a user
- Log in and receive tokens
- Access a protected endpoint
- Test failure cases
- JWT Authentication Security Best Practices
- Common JWT Authentication Errors
- Conclusion
- Frequently Asked Questions
- What is JWT authentication in Node.js?
- How does JWT authentication work in REST APIs?
- Is JWT more secure than session-based authentication?
- What is the difference between an access token and a refresh token?
- Where should JWT tokens be stored?
- Can JWT tokens be reused after expiration?
- How do you protect REST API routes using JWT?
- Is JWT suitable for production applications?
TL;DR
- A JWT is a signed token with three parts: header, payload and signature. The server verifies it without a session lookup.
- The login flow is: verify credentials, sign a token, return it, then validate it on every protected request.
- Use short-lived access tokens (about 15 minutes) and longer-lived refresh tokens that can be rotated and revoked.
- Hash passwords with bcrypt, keep secrets in environment variables, and never put sensitive data in the payload.
- Serve everything over HTTPS and rate-limit login endpoints.
What Is JWT Authentication?
A JSON Web Token is a compact, URL-safe string that carries claims about a user and is signed by the server. Because the signature proves the token has not been altered, the API can trust its contents without querying a session store. That is why JWT token authentication suits stateless REST APIs and horizontally scaled services.
This JSON Web Token tutorial starts with the structure. Every JWT has three Base64URL-encoded parts separated by dots:
xxxxx.yyyyy.zzzzz
header.payload.signature
Header
Describes the token type and the signing algorithm, for example { “alg”: “HS256”, “typ”: “JWT” }.
Payload
Holds the claims: the user ID (sub or a custom id), the issue time (iat) and the expiry (exp). The payload is encoded, not encrypted, so anyone holding the token can read it.
Signature
The server signs the encoded header and payload with a secret key. If anyone changes a single character, verification fails.
Ready to take your full-stack development skills to the next level? Enrol in our comprehensive Full-Stack Development Course and master both front-end and back-end development. Gain hands-on experience with Java, Spring Boot, Hibernate, Angular, and React while learning to build secure, scalable, and dynamic web applications. Develop practical skills through real-world projects and prepare yourself for exciting full-stack development opportunities. Start learning today!
How JWT Authentication Works in a REST API
The flow has six steps:
- The user submits an email and password to the login endpoint.
- The server looks up the user and compares the password with the stored hash.
- If it matches, the server signs a JWT containing the user’s ID.
- The client receives the token and stores it.
- The client sends the token in the Authorization: Bearer <token> header on later requests.
- The server verifies the signature and expiry before it grants access.
Client Server
| -- POST /login (email, password) --> | verify password hash
| <-- 200 { accessToken, refreshToken } | sign JWT
| |
| -- GET /profile |
| Authorization: Bearer <token> ---> | verify signature + expiry
| <-- 200 { user data } -------------- | (or 401 if invalid)
Prerequisites and Project Setup
You need basic JavaScript and REST API knowledge, plus these tools:
- Node.js (v18 or later) and Express.js for the server
- MongoDB (local or Atlas) with Mongoose for data modelling
- jsonwebtoken to sign and verify tokens
- bcryptjs to hash passwords
- dotenv to load environment variables
- Postman to test the endpoints
Create the project and install the dependencies:
mkdir jwt-auth-demo && cd jwt-auth-demo
npm init -y
npm install express mongoose jsonwebtoken bcryptjs dotenv
npm install --save-dev nodemon
Use this structure:
jwt-auth-demo/
├── models/User.js
├── middleware/auth.js
├── routes/auth.js
├── .env
└── server.js
Add your secrets to .env, and keep this file out of version control:
PORT=5000
MONGO_URI=mongodb://127.0.0.1:27017/jwt_auth_demo
JWT_ACCESS_SECRET=replace_with_a_long_random_string
JWT_REFRESH_SECRET=replace_with_a_different_long_random_string
Build JWT Authentication in Node.js
The snippets below form one working application. Create each file as shown.
Step 1: Create the Express server and connect MongoDB
server.js loads the environment variables, connects to MongoDB, mounts the auth routes and exposes one protected route. The server starts only after the database connection succeeds.
// server.js
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const authRoutes = require("./routes/auth");
const auth = require("./middleware/auth");
const app = express();
app.use(express.json());
app.use("/api/auth", authRoutes);
app.get("/api/profile", auth, (req, res) => {
res.json({ message: "Protected data", userId: req.user.id });
});
mongoose
.connect(process.env.MONGO_URI)
.then(() => {
console.log("MongoDB connected");
app.listen(process.env.PORT, () =>
console.log(`Server running on port ${process.env.PORT}`)
);
})
.catch((err) => {
console.error("Database connection failed:", err.message);
process.exit(1);
});
Step 2: Create the user model and hash passwords
The schema stores a refreshTokens array, which the refresh flow later uses for rotation and revocation. The pre(“save”) hook hashes the password with bcrypt (12 salt rounds) whenever it changes, so plain-text passwords never reach the database.
// models/User.js
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const userSchema = new mongoose.Schema({
name: { type: String, required: true, trim: true },
email: { type: String, required: true, unique: true, lowercase: true, trim: true },
password: { type: String, required: true, minlength: 8 },
refreshTokens: [String],
});
userSchema.pre("save", async function () {
if (!this.isModified("password")) return;
this.password = await bcrypt.hash(this.password, 12);
});
userSchema.methods.matchPassword = function (plainPassword) {
return bcrypt.compare(plainPassword, this.password);
};
module.exports = mongoose.model("User", userSchema);
Step 3: Implement registration, login and token generation
The routes file handles four things. /register creates a user, and the model hook hashes the password. /login checks the password and returns an access token and a refresh token. /refresh swaps a valid refresh token for a new pair. /logout revokes the refresh token.
Both login failures return the same message. That stops attackers from learning which emails are registered. Each refresh token also gets a unique jwtid, so two tokens issued in the same second are never identical.
// routes/auth.js
const express = require("express");
const jwt = require("jsonwebtoken");
const { randomUUID } = require("crypto");
const User = require("../models/User");
const router = express.Router();
const signAccessToken = (id) =>
jwt.sign({ id }, process.env.JWT_ACCESS_SECRET, { expiresIn: "15m" });
const signRefreshToken = (id) =>
jwt.sign({ id }, process.env.JWT_REFRESH_SECRET, {
expiresIn: "7d",
jwtid: randomUUID(),
});
router.post("/register", async (req, res) => {
try {
const { name, email, password } = req.body;
if (await User.findOne({ email })) {
return res.status(409).json({ message: "Email already registered" });
}
const user = await User.create({ name, email, password });
res.status(201).json({ id: user.id, name: user.name, email: user.email });
} catch (err) {
res.status(400).json({ message: err.message });
}
});
router.post("/login", async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ message: "Email and password are required" });
}
const user = await User.findOne({ email });
if (!user || !(await user.matchPassword(password))) {
return res.status(401).json({ message: "Invalid email or password" });
}
const accessToken = signAccessToken(user.id);
const refreshToken = signRefreshToken(user.id);
user.refreshTokens.push(refreshToken);
await user.save();
res.json({ accessToken, refreshToken });
} catch (err) {
res.status(500).json({ message: "Server error" });
}
});
router.post("/refresh", async (req, res) => {
const { refreshToken } = req.body;
if (!refreshToken) {
return res.status(400).json({ message: "Refresh token required" });
}
try {
const payload = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET, {
algorithms: ["HS256"],
});
const user = await User.findById(payload.id);
if (!user || !user.refreshTokens.includes(refreshToken)) {
return res.status(403).json({ message: "Refresh token revoked or reused" });
}
// Rotation: remove the used token, issue a new pair
const newRefreshToken = signRefreshToken(user.id);
user.refreshTokens = user.refreshTokens.filter((t) => t !== refreshToken);
user.refreshTokens.push(newRefreshToken);
await user.save();
res.json({ accessToken: signAccessToken(user.id), refreshToken: newRefreshToken });
} catch (err) {
res.status(401).json({ message: "Invalid or expired refresh token" });
}
});
router.post("/logout", async (req, res) => {
try {
const { refreshToken } = req.body;
const payload = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET);
await User.updateOne({ _id: payload.id }, { $pull: { refreshTokens: refreshToken } });
} catch (err) {
// An invalid token is already unusable, so logout still succeeds
}
res.json({ message: "Logged out" });
});
module.exports = router;
Step 4: Create the authentication middleware and protect routes
The middleware reads the Authorization header, checks the Bearer format, verifies the signature and expiry, and attaches the decoded payload to req.user. Any route that includes auth is now protected, like /api/profile in server.js.
// middleware/auth.js
const jwt = require("jsonwebtoken");
module.exports = (req, res, next) => {
const header = req.headers.authorization;
if (!header || !header.startsWith("Bearer ")) {
return res.status(401).json({ message: "Missing or malformed Authorization header" });
}
const token = header.split(" ")[1];
try {
req.user = jwt.verify(token, process.env.JWT_ACCESS_SECRET, { algorithms: ["HS256"] });
next();
} catch (err) {
const message = err.name === "TokenExpiredError" ? "Token expired" : "Invalid token";
res.status(401).json({ message });
}
};
Start the app with npx nodemon server.js.
JWT Access Token vs Refresh Token
A JWT access token and refresh token solve different problems. The access token proves identity on each API call, so it must expire quickly in case it leaks. The refresh token lets the user stay signed in without typing a password again.
| Access token | Refresh token | |
| Purpose | Authorizes API requests | Obtains new access tokens |
| Expiration | Short (for example, 15 minutes) | Longer (for example, 7 days) |
| Usage | Sent with every protected request | Sent only to the /refresh and /logout endpoints |
| Signing secret | JWT_ACCESS_SECRET | A separate JWT_REFRESH_SECRET |
| Security considerations | Stateless, so it cannot be revoked before expiry | Stored server-side so it can be revoked; a stolen one is high-risk |
When the access token expires, the client sends the refresh token to /api/auth/refresh and receives a new pair.
Rotation: every refresh issues a new refresh token and deletes the old one. If an old token is presented again, the server rejects it with a 403, which signals possible theft.
Revocation: because valid refresh tokens live in the user’s refreshTokens array, removing one (logout) or clearing the array (a security reset) invalidates it immediately.
Also Read: 30 Sure Shot Cybersecurity Interview Questions and Answers
Test the JWT Authentication System Using Postman
With the server running, set the body type to raw → JSON for each POST request.
1. Register a user
POST http://localhost:5000/api/auth/register
{ "name": "Asha", "email": "[email protected]", "password": "Str0ngPass!" }
Expected: 201 Created with the user’s id, name and email. The password is not returned.
2. Log in and receive tokens
POST http://localhost:5000/api/auth/login with the email and password.
{ "accessToken": "eyJhbGciOi...", "refreshToken": "eyJhbGciOi..." }
3. Access a protected endpoint
GET http://localhost:5000/api/profile. Open the Authorization tab, choose Bearer Token and paste the access token.
{ "message": "Protected data", "userId": "6650f1c2..." }
4. Test failure cases
To test expiry quickly, temporarily set the access token’s expiresIn to “10s”, log in, wait, and call /api/profile again. Then call /api/auth/refresh with your refresh token to get a new pair.
JWT Authentication Security Best Practices
A working login is not yet a secure one. Apply these measures before production:
- Use strong secrets from the environment. Generate long random values, keep them out of source control, and use different secrets for access and refresh tokens.
- Keep access tokens short-lived. Minutes, not days. A leaked token then stays useful for only a short time.
- Use HTTPS everywhere. Tokens sent over plain HTTP can be intercepted.
- Validate signatures and claims. Pin the allowed algorithm (algorithms: [“HS256”]), as the code above does, and check exp. Add issuer and audience checks if several services share tokens.
- Keep the payload minimal. Store only an ID. Never include passwords or personal data, because the payload is readable by anyone.
- Secure refresh-token storage. Store refresh tokens server-side so they can be revoked. In production, consider storing a hash of each token rather than the raw value.
- Rotate and revoke refresh tokens. Rotate on every refresh, and clear a user’s tokens on password change or suspected compromise.
- Rate-limit authentication endpoints. A package such as express-rate-limit on /login and /register slows brute-force attempts.
- Prefer HttpOnly cookies in browsers. Sending the refresh token in a Secure, HttpOnly, SameSite cookie keeps it out of reach of JavaScript, which limits damage from XSS. If you use cookies, add CSRF protection.
Common JWT Authentication Errors
| Error | Likely cause | Fix |
| JsonWebTokenError: invalid token | Token is malformed, truncated or edited | Copy the full token again and check for stray quotes or spaces |
| TokenExpiredError: jwt expired | The exp time has passed | Call /api/auth/refresh to get a new access token |
| Missing or malformed Authorization header | Header absent, or not in Bearer <token> form | Send Authorization: Bearer <token> with one space |
| JsonWebTokenError: invalid signature | Token was signed with a different secret | Check that .env values match and the server was restarted after changes |
| secret or public key must be provided | JWT_ACCESS_SECRET is undefined | Confirm dotenv loads before the routes and the variable name is spelled correctly |
| Refresh returns 403 | Token was already rotated or revoked | Log in again to start a new session |
Conclusion
JWT authentication lets a REST API verify callers without storing sessions. In this JWT authentication tutorial you built a complete login system: registration with bcrypt-hashed passwords, a login endpoint that issues access and refresh tokens, a refresh endpoint with rotation, logout with revocation, and middleware that protects routes.
The code is a solid foundation, but production safety depends on how you handle tokens. Keep secrets in the environment, expire access tokens quickly, serve over HTTPS, rate-limit login attempts, and store refresh tokens carefully. Next, try adding role-based access control by putting a role claim in the access token and checking it in the middleware.
Frequently Asked Questions
1. What is JWT authentication in Node.js?
It is a method where an Express server signs a JSON Web Token with the jsonwebtoken library after a successful login. The client then sends that token on later requests, and middleware verifies it before allowing access.
2. How does JWT authentication work in REST APIs?
The client logs in, the server returns a signed token, and the client attaches it to each request in the Authorization header. The server checks the signature and expiry on every call, with no session lookup.
3. Is JWT more secure than session-based authentication?
Not inherently. Sessions can be revoked instantly because the server holds the state. JWTs scale easily without shared storage but cannot be revoked before expiry unless you add a revocation mechanism. Both are secure when implemented correctly.
4. What is the difference between an access token and a refresh token?
An access token is short-lived and authorizes API requests. A refresh token lasts longer and is used only to get new access tokens.
5. Where should JWT tokens be stored?
For browser apps, keep refresh tokens in Secure, HttpOnly cookies. Keep access tokens in memory where possible. Avoid localStorage for sensitive tokens, since any XSS flaw can read it. Mobile apps should use the platform’s secure storage.
6. Can JWT tokens be reused after expiration?
No. Once the exp time passes, verification fails and the server rejects the token. The client must use a valid refresh token to get a new access token.
7. How do you protect REST API routes using JWT?
Add authentication middleware that verifies the token, then place it before the route handler, as in app.get(“/api/profile”, auth, handler). Requests without a valid token get a 401 response.
8. Is JWT suitable for production applications?
Yes, when used with short expiries, HTTPS, strong secrets, refresh-token rotation and revocation. Many production APIs use it. For systems that need instant logout everywhere, pair it with server-side token tracking or consider sessions.



Did you enjoy this article?