For users to safely log in and access resources without revealing personal information, any online application needs to be secure. The JSON Web Token (JWT) is one of the most popular ways to manage authentication and permission in Node.js. JWT offers a condensed, standalone technique for safely sending data as a JSON object between parties.
This blog will discuss:
- The meaning of authorization and authentication.
- Why JWT is so popular.
- How to set up authentication in a Node.js application using JWT.
- JWT security best practices.
Authentication vs Authorization
Let’s define the distinction between authorization and authentication before moving on to implementation:
- Authentication, such as using a username and password to log in, confirms the identity of the user.
- After authentication, authorization controls the user’s access (e.g., allowing an admin user to remove records).
- JWT facilitates the effective management of both procedures in web applications.ations.
Why Use JWT for Authentication?
JWT is a popular authentication mechanism because:
- Stateless – No need to store session data on the server.
- Compact and Secure – Uses a signed token to transmit user data.
- Easy to Implement – Works well with RESTful APIs.
- Cross-Domain Support – Works across different platforms (mobile, web, backend services).
How JWT Works in Node.js
- The user logs in with their credentials.
- If valid, the server generates a JWT and sends it to the client.
- The client includes the token in the headers of future requests.
- The server verifies the token and grants or denies access to resources.
Setting Up JWT Authentication in Node.js
Let’s implement JWT authentication using Express.js and jsonwebtoken.
Step 1: Install Dependencies
Ensure you have Node.js installed, then run:
npm init -y # Initialize a new project
npm install express jsonwebtoken bcryptjs dotenv
express: Web framework for Node.js.jsonwebtoken: For generating and verifying JWTs.bcryptjs: For hashing passwords.dotenv: For environment variables.
Step 2: Create a Basic Express Server
Create server.js and set up an Express app:
const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const dotenv = require("dotenv");
dotenv.config();
const app = express();
app.use(express.json());
const users = []; // In-memory user storage (replace with DB in production)
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Step 3: User Registration
Hash the user’s password before storing it:
app.post("/register", async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
users.push({ username, password: hashedPassword });
res.status(201).json({ message: "User registered successfully" });
});
Step 4: User Login & Token Generation
Validate user credentials and issue a JWT:
app.post("/login", async (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).json({ message: "Invalid credentials" });
}
const token = jwt.sign({ username: user.username }, process.env.JWT_SECRET, { expiresIn: "1h" });
res.json({ token });
});
Step 5: Protect Routes with JWT Middleware
Create a middleware to verify JWT tokens:
const authenticateToken = (req, res, next) => {
const token = req.header("Authorization");
if (!token) return res.status(403).json({ message: "Access denied" });
jwt.verify(token.split(" ")[1], process.env.JWT_SECRET, (err, user) => {
if (err) return res.status(403).json({ message: "Invalid token" });
req.user = user;
next();
});
};
Step 6: Create a Protected Route
Only authenticated users can access this:
app.get("/protected", authenticateToken, (req, res) => {
res.json({ message: "Welcome to the protected route, " + req.user.username });
});
Best Practices for JWT Security
- Use Effective Secrets Keep your JWT_SECRET in a.env file and use a strong key.
- Set Token Expiry: Short-lived tokens (expiresIn: “1h”) reduce the likelihood of misuse.
- Use HTTPS: Secure connections prevent the interception of tokens.
- Consider keeping revoked tokens in a database when you’re logging out.
- Use Refresh Tokens: Provide users with persistent refresh tokens to reauthenticate them.
In conclusion
JWT is a useful technique for integrating authentication and permission in Node.js applications. By following suggested procedures, you may preserve system security while preserving a seamless user experience..
How Backend Development Powers Modern Web Applications
Which Framework Should I Learn in 2025?

WhatsApp us