Authentication with JWT

Node js 12 min min read Updated: Mar 30, 2026 Intermediate
Authentication with JWT
Intermediate Topic 6 of 10

Authentication with JWT in Node.js

Authentication is one of the most important parts of backend development. It helps verify the identity of users and ensures that only authorized people can access protected resources.

One of the most widely used methods for authentication in modern web applications is JWT, which stands for JSON Web Token. JWT allows secure communication between the client and server by sending digitally signed tokens.

Key Concept: JWT is a compact and secure token format used to verify user identity and protect API routes.

What is JWT?

JWT stands for JSON Web Token. It is a compact, URL-safe token format used for authentication and authorization.

After a user successfully logs in, the server generates a token and sends it to the client. The client then stores the token and includes it in future requests, usually in the Authorization header.

Why Use JWT?

  • Stateless authentication: Server does not need to store session data
  • Secure: Tokens are signed and can be verified
  • Scalable: Works well with APIs and distributed systems
  • Widely used: Common in web and mobile applications

Structure of a JWT

A JWT consists of three parts separated by dots:

  • Header: Contains token type and algorithm
  • Payload: Contains user data or claims
  • Signature: Verifies that the token was not modified

Example:

text header.payload.signature

Installing JWT Package

To use JWT in Node.js, install the jsonwebtoken package:

bash npm install jsonwebtoken

Generating a JWT Token

After login, you can generate a token like this:

javascript const jwt = require("jsonwebtoken"); const token = jwt.sign( { userId: 1, email: "rahul@example.com" }, "secretkey", { expiresIn: "1h" } ); console.log(token);

In this example:

  • jwt.sign() creates a new token
  • The payload contains user details
  • "secretkey" is used to sign the token
  • expiresIn sets the token expiry time

Verifying a JWT Token

To check whether a token is valid, use jwt.verify():

javascript const decoded = jwt.verify(token, "secretkey"); console.log(decoded);

If the token is valid, the decoded payload is returned. If it is invalid or expired, an error is thrown.

JWT Authentication Middleware

In Express.js, JWT is commonly used in middleware to protect routes.

javascript const jwt = require("jsonwebtoken"); function authMiddleware(req, res, next) { const token = req.header("Authorization"); if (!token) { return res.status(401).json({ message: "Access denied" }); } try { const verified = jwt.verify(token, "secretkey"); req.user = verified; next(); } catch (err) { res.status(400).json({ message: "Invalid token" }); } }

Using JWT to Protect Routes

Once middleware is created, you can use it on protected routes:

javascript app.get("/profile", authMiddleware, (req, res) => { res.json({ message: "Welcome to your profile", user: req.user }); });

This ensures that only users with a valid token can access the /profile route.

How JWT Authentication Works

  1. User logs in with email and password
  2. Server verifies credentials
  3. Server generates JWT token
  4. Client stores token
  5. Client sends token with future requests
  6. Server verifies token before allowing access

Where to Store JWT on Client Side

JWT can be stored in:

  • Local Storage – easy to use, but vulnerable to XSS if your site is compromised
  • HTTP-only Cookies – more secure against direct JavaScript access and often preferred for web apps

For stronger security in browser-based apps, many teams prefer HTTP-only cookies with proper CSRF protection.

Best Practices for JWT Authentication

  • Use strong secret keys
  • Set token expiration time
  • Never store sensitive data in payload
  • Use HTTPS in production
  • Prefer environment variables for secrets
  • Combine JWT with refresh token strategy for long-lived sessions

Common Mistakes

  • Using weak secret keys
  • Not setting token expiry
  • Storing passwords inside JWT payload
  • Not handling invalid or expired tokens properly

JWT vs Session Authentication

Feature JWT Session
Storage Client side Server side
Scalability High Moderate
State Stateless Stateful
Best For APIs and mobile apps Traditional web apps

Real-World Use Cases

  • User login systems
  • Protecting REST APIs
  • Mobile application authentication
  • Role-based access systems

Conclusion

JWT is a popular and effective way to implement authentication in Node.js applications. It provides a secure, scalable, and stateless method for verifying users and protecting API routes.

Once you understand how to generate, verify, and use JWT in middleware, you can build secure login systems and protected backend applications more confidently.

Quick Summary: JWT is a signed token used to authenticate users and protect routes in Node.js applications without storing sessions on the server.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators