How to use JWT for authentication on Node.js

Published: (January 14, 2026 at 11:49 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Cover image for How to use JWT for authentication on Node.js

What is JWT?

JWT (JSON Web Token) is a compact, URL‑safe token used to securely transmit information between parties.

A JWT looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

It consists of three parts:

HEADER.PAYLOAD.SIGNATURE

JWT Structure

Contains token type and signing algorithm.

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

Contains user data (claims).

{
  "id": 42,
  "email": "user@example.com"
}

⚠️ Never store passwords or other sensitive data in the payload.

Signature

Used to verify the token wasn’t modified.

HMACSHA256(base64UrlHeader + "." + base64UrlPayload, secret)

How JWT Authentication Works

  1. User logs in with email & password.
  2. Server verifies credentials.
  3. Server generates a JWT.
  4. Client stores the JWT (usually in memory or an HTTP‑only cookie).
  5. Client sends the JWT in the Authorization header.
  6. Server verifies the JWT on every request.

Implementing JWT Auth in Node.js (Express)

Install Dependencies

npm install express auth-verify

Generate (signing) JWT on Login

const AuthVerify = require('auth-verify');
const auth = new AuthVerify({
  jwtSecret: "SUPER_SECRET" // secret for signing JWTs
});

// Generate a JWT that expires in 1 hour
auth.jwt.sign({ userId: 1, user: "John Doe" }, "1h");

Login Route Example

const express = require('express');
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const AuthVerify = require('auth-verify');
const auth = new AuthVerify({ jwtSecret: "SUPER_SECRET" });

app.post('/login', async (req, res) => {
  const { email, password } = req.body;

  const user = await findUserByEmail(email);
  if (!user) return res.status(401).json({ message: 'Invalid credentials' });

  const isValid = await auth.crypto.verify(password, user.password);
  if (!isValid) return res.status(401).json({ message: 'Invalid credentials' });

  const token = await auth.jwt.sign({ userId: user.id, user: user.name }, "1h");
  res.json({ token });
});

Protecting Routes with JWT Middleware

auth.jwt.protect(); // returns Express middleware

Protected Route Example

app.get('/profile', auth.jwt.protect(), (req, res) => {
  res.json({
    message: 'Welcome!',
    user: req.user
  });
});

Sending JWT from Client

Authorization: Bearer YOUR_JWT_TOKEN

Common JWT Mistakes

  • ❌ Storing JWT in localStorage (XSS risk)
  • ❌ Putting sensitive data inside the payload
  • ❌ Not setting token expiration
  • ❌ Using weak secrets

Best practices

  • ✅ Use HTTP‑only cookies when possible
  • ✅ Always set expiresIn (or exp claim)
  • ✅ Rotate secrets in production

When Should You Use JWT?

Great for:

  • Stateless APIs
  • Microservices architectures
  • Mobile or SPA authentication

Not ideal when:

  • You need instant logout across all clients
  • You require heavy session control

Conclusion

JWT provides a simple, scalable, and stateless way to handle authentication.
When used correctly, it’s powerful and secure. If you’re building APIs, SPAs, or mobile apps — JWT is worth mastering.

Back to Blog

Related posts

Read more »

Entendendo o JSON Web Token (JWT)

Em algum momento, ao criar uma aplicação web, precisamos desenvolver uma solução de autenticação para o sistema. Existem várias estratégias para isso, como aute...