How to Implement JWT Authentication in Node.js: A Step-by-Step Tutorial
JWT (JSON Web Token) authentication is a popular method for securing Node.js APIs. It allows stateless authentication by issuing signed tokens that clients send with each request. Unlike session-based auth, JWTs are self-contained and scalable.
In this tutorial, you’ll learn how to set up JWT authentication in a Node.js Express app, from generating tokens to protecting routes. We’ll cover installation, token generation, middleware, and testing.

1. Install Dependencies and Set Up Express
Start by initializing a Node.js project and installing the required packages: express, jsonwebtoken, and bcrypt for password hashing.
npm init -ynpm install express jsonwebtoken bcrypt
Create a basic Express server with a secret key stored in an environment variable.
2. Generate and Sign JWT Tokens
When a user logs in, verify their credentials and generate a token using jwt.sign(). Include a payload like user ID and set an expiration time.
- Use
jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' }). - Return the token to the client in the response.
3. Create Authentication Middleware
Write a middleware function to verify the token from the Authorization header. If valid, attach the decoded user to req.user and call next().
- Extract token:
const token = req.headers.authorization?.split(' ')[1]. - Verify with
jwt.verify()and handle errors.
4. Protect Routes and Test
Apply the middleware to protected routes. Use tools like Postman to test login and access with the token.
app.get('/protected', authenticate, (req, res) => res.json({ message: 'Access granted' })).- Ensure tokens are sent in the
Authorization: Bearer <token>format.
That’s it! You’ve implemented JWT authentication in Node.js. Remember to keep your secret key safe and use HTTPS in production.