How to Implement JWT Authentication in Node.js
A step-by-step guide on how to implement stateless authentication using JSON Web Tokens in a Node.js Express API.
Understand How JWT Works
A JSON Web Token is a compact, self-contained string that encodes information called claims. It consists of three parts separated by dots: a header containing the algorithm, a payload containing the user data, and a signature. The server signs the token with a secret key. When the client sends the token back, the server verifies the signature to confirm authenticity without querying a database.
Install and Configure jsonwebtoken
Install the jsonwebtoken package from npm. Store your JWT secret key in an environment variable, never hardcode it in your source code. The secret should be a long, random, unpredictable string. Use the dotenv package to load environment variables from a .env file during development and configure your deployment environment to provide them in production.
Generate a Token on Login
In your login controller, after verifying the user's credentials against the database, call jwt.sign with a payload object containing the user's ID and role, the secret key from your environment variables, and an options object specifying the expiration time such as '7d' for seven days. Send the resulting token in the response body for the client to store.
Create the Authentication Middleware
Write an Express middleware function that extracts the token from the Authorization header. The header value follows the format 'Bearer token'. Split the header value on the space and take the second element. If no token is present, call next with a 401 Unauthorized error immediately.
Verify the Token in Middleware
Inside the auth middleware, call jwt.verify with the extracted token and the secret key. Wrap this in a try-catch. If verification succeeds, jwt.verify returns the decoded payload. Attach this decoded payload to req.user so downstream route handlers and controllers can access the authenticated user's identity. Then call next to pass control to the next middleware.
Handle Token Verification Failures
In the catch block of jwt.verify, check the error type. A JsonWebTokenError means the token is malformed or the signature is invalid. A TokenExpiredError means the token has passed its expiration time. Send appropriate 401 responses with clear error messages for each case. Never send the raw JWT error message to clients as it can reveal implementation details.
Protect Routes with the Middleware
Apply the auth middleware to any route that requires authentication. Pass it as a second argument before the route handler in Express. Apply it to an entire router using router.use to protect all routes in that router at once. Leave public routes like login and registration without the middleware so unauthenticated users can access them.
Implement Refresh Tokens
Short-lived access tokens expire quickly for security. Implement refresh tokens to allow users to get new access tokens without logging in again. Issue a long-lived refresh token at login and store its hash in the database. Provide a dedicated endpoint that accepts a valid refresh token, verifies it against the database, and issues a new short-lived access token. Invalidate refresh tokens on logout by deleting them from the database.
Ready to master this completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

