JWT Authentication in Node.js
JWT (JSON Web Token) is a way to securely transmit verified information between a client and a server. In Node.js applications, JWT is commonly used to authenticate users and protect API endpoints.
1. What Is JWT?
JWT stands for JSON Web Token. After a user successfully logs in, the server can generate a signed token and send it to the client. The client then sends this token with requests to protected APIs.
A JWT commonly contains three parts:
| Part | Purpose |
|---|---|
| Header | Identifies the token type and signing algorithm. |
| Payload | Contains claims such as the user's ID and token expiry. |
| Signature | Allows the server to verify that the token has not been modified. |
2. Why Do We Use JWT?
- To authenticate users after login.
- To protect APIs from unauthenticated requests.
- To identify the user making a request.
- To validate a token's signature and expiration.
- To avoid requiring a traditional server-side session for every API request.
3. Install Required Packages
Open your terminal in the Node.js project folder and run:
npm install express bcrypt jsonwebtoken mysql2 dotenv
These packages are used for the following purposes:
| Package | Purpose |
|---|---|
| express | Creates API routes and middleware. |
| bcrypt | Compares the submitted password with its stored hash. |
| jsonwebtoken | Creates and verifies JWT tokens. |
| mysql2 | Connects to the MySQL database. |
| dotenv | Loads configuration values from the .env file. |
4. Configure the JWT Secret
Create a .env file in the project root. Keep the signing
secret private and never commit it to source control.
JWT_SECRET=replace_with_a_strong_random_secret
JWT_ISSUER=node-auth-demo
JWT_AUDIENCE=node-auth-api
Generate a strong random secret using Node.js:
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
Replace the placeholder with the generated value. Add .env
to .gitignore so the secret is not committed.
5. How JWT Authentication Works
The user submits an email and password.
The server checks the user record and password hash.
The server signs a token and returns it to the client.
The client sends the token in the Authorization header.
The server verifies the token before returning protected data.
6. Generate a JWT After Login
In the previous User Login page, we checked the user's email and password. Now we will update that login endpoint so a successful login also returns a JWT.
const express = require("express");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const db = require("./db");
const router = express.Router();
router.post("/login", async (req, res) => {
try {
const { email, password } = req.body;
if (
typeof email !== "string" ||
typeof password !== "string" ||
!email.trim() ||
!password
) {
return res.status(400).json({
message: "Email and password are required."
});
}
const [users] = await db.execute(
"SELECT id, name, email, password_hash FROM users WHERE email = ?",
[email.trim()]
);
if (users.length === 0) {
return res.status(401).json({
message: "Invalid email or password."
});
}
const user = users[0];
const passwordMatches = await bcrypt.compare(
password,
user.password_hash
);
if (!passwordMatches) {
return res.status(401).json({
message: "Invalid email or password."
});
}
if (!process.env.JWT_SECRET) {
throw new Error("JWT_SECRET is not configured.");
}
const token = jwt.sign(
{ sub: String(user.id) },
process.env.JWT_SECRET,
{
expiresIn: "15m",
issuer: process.env.JWT_ISSUER,
audience: process.env.JWT_AUDIENCE
}
);
return res.status(200).json({
message: "Login successful.",
token,
tokenType: "Bearer",
expiresIn: 900,
user: {
id: user.id,
name: user.name,
email: user.email
}
});
} catch (error) {
console.error("Login error:", error);
return res.status(500).json({
message: "An internal server error occurred."
});
}
});
module.exports = router;
id, name, email, and
password_hash columns. Match these names to your actual schema.
The sub claim identifies the user. The token expires after
15 minutes, so the client must sign in again or use a separately implemented
refresh-token flow when it expires.
7. Create JWT Authentication Middleware
Middleware runs before a protected route. It checks whether the request contains a valid Bearer token.
const jwt = require("jsonwebtoken");
function authenticateToken(req, res, next) {
const authorization = req.headers.authorization;
if (!authorization || !authorization.startsWith("Bearer ")) {
return res.status(401).json({
message: "Authentication token is required."
});
}
const token = authorization.slice(7).trim();
if (!token) {
return res.status(401).json({
message: "Authentication token is required."
});
}
try {
const decoded = jwt.verify(
token,
process.env.JWT_SECRET,
{
issuer: process.env.JWT_ISSUER,
audience: process.env.JWT_AUDIENCE,
algorithms: ["HS256"]
}
);
if (typeof decoded.sub !== "string") {
return res.status(401).json({
message: "Invalid authentication token."
});
}
req.user = {
id: decoded.sub
};
next();
} catch (error) {
return res.status(401).json({
message: "Invalid or expired authentication token."
});
}
}
module.exports = authenticateToken;
jwt.verify() checks the token's signature, expiration,
issuer, and audience. If verification fails, the request is rejected.
8. Protect an API Route
After creating the middleware, apply it to routes that require a logged-in user.
require("dotenv").config();
const express = require("express");
const authenticateToken = require("./authMiddleware");
const authRoutes = require("./authRoutes");
const app = express();
app.use(express.json());
app.use("/api/auth", authRoutes);
app.get("/api/auth/me", authenticateToken, (req, res) => {
res.status(200).json({
message: "Protected API accessed successfully.",
userId: req.user.id
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
dotenv before using
process.env. Keep your existing database setup in
db.js and make sure the route file imports the correct pool.
9. Test JWT Authentication in Postman
Step 1: Login
Send a POST request to:
http://localhost:3000/api/auth/login
Select Body → raw → JSON:
{
"email": "user@example.com",
"password": "YourPasswordHere"
}
After a successful login, copy the token value from the response.
Step 2: Call the Protected API
Send a GET request to:
http://localhost:3000/api/auth/me
In Postman, open the Authorization tab, select Bearer Token, and paste the token.
Expected Successful Response
{
"message": "Protected API accessed successfully.",
"userId": "1"
}
The user ID shown here is only an example. Your response will contain the ID represented by the verified token.
10. Common HTTP Status Codes
| Status Code | Meaning |
|---|---|
| 200 OK | Login or protected request succeeded. |
| 400 Bad Request | Required login information is missing or invalid. |
| 401 Unauthorized | Credentials or token are invalid, missing, or expired. |
| 403 Forbidden | The user is authenticated but lacks permission for an action. |
| 500 Internal Server Error | An unexpected server-side error occurred. |
11. JWT Security Best Practices
- Use a strong, private signing secret and rotate it when necessary.
- Use HTTPS in production.
- Set a reasonable token expiration time.
- Never include passwords or other secrets in the token payload.
- Validate the token's signature, issuer, audience, and expiration.
- Apply login rate limiting and input validation.
- Do not assume a valid token automatically grants administrator permissions.
- For browser applications, carefully evaluate secure HttpOnly cookies with appropriate SameSite settings. Protect cookie-based requests against CSRF.
- Remember that a JWT normally remains usable until expiry unless you implement revocation or another invalidation strategy.
Important Points to Remember
- JWT stands for JSON Web Token.
jwt.sign()creates a signed token.jwt.verify()verifies the token.- The client sends the token using the Bearer authorization scheme.
- Authentication middleware protects API endpoints.
- A signed JWT is not the same as an encrypted JWT.
- Authorization rules must be implemented separately.
Summary
JWT authentication allows a Node.js server to issue a signed token after
successful login and verify it on later requests. By combining
jsonwebtoken, authentication middleware, token expiry, and
secure secret management, you can protect APIs from unauthenticated access.
In the next lesson, we will learn Authorization and Protected Routes.