agyanadda@gmail.com

Node.js Authentication with JWT

Express.js and Databases 1 min read Updated Dec 3, 2026 Topic 22 of 30

Most APIs use token authentication: after login, the server gives the client a token, and the client sends it with every request.

JSON Web Token (JWT)

A JWT has three parts: header.payload.signature. The payload holds data such as the user id. The signature, made with a secret key, proves the token was not changed. The payload is only encoded, not encrypted — never put passwords in it.

Packages

npm install bcrypt jsonwebtoken

The flow

  1. Register: hash the password with bcrypt.hash(password, 10) and save the user
  2. Login: find the user, check with bcrypt.compare(), then jwt.sign({ sub: user.id }, SECRET, { expiresIn: '1h' })
  3. The client sends Authorization: Bearer <token>
  4. Middleware verifies with jwt.verify() and sets req.user

Security tips

  • Keep JWT_SECRET long and in .env
  • Use short expiry times; refresh tokens for long sessions
  • Always use HTTPS
  • Rate-limit the login route

For browser apps, storing the token in an httpOnly cookie protects it from JavaScript (XSS).

Example

Example — Login and protected route JavaScript
import express from 'express';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';

const app = express();
app.use(express.json());
const users = [];   // use a real database in your app
const SECRET = process.env.JWT_SECRET;

app.post('/api/register', async (req, res) => {
  const { email, password } = req.body;
  if (users.some((u) => u.email === email)) return res.status(409).json({ error: 'Email already registered' });
  users.push({ id: users.length + 1, email, password: await bcrypt.hash(password, 10) });
  res.status(201).json({ message: 'Registered' });
});

app.post('/api/login', async (req, res) => {
  const user = users.find((u) => u.email === req.body.email);
  if (!user || !(await bcrypt.compare(req.body.password, user.password))) {
    return res.status(401).json({ error: 'Invalid email or password' });
  }
  const token = jwt.sign({ sub: user.id, email: user.email }, SECRET, { expiresIn: '1h' });
  res.json({ token });
});

function auth(req, res, next) {
  const token = req.get('authorization')?.replace('Bearer ', '');
  try {
    req.user = jwt.verify(token, SECRET);
    next();
  } catch {
    res.status(401).json({ error: 'Please log in' });
  }
}

app.get('/api/me', auth, (req, res) => res.json({ id: req.user.sub, email: req.user.email }));
app.listen(3000);

Register, then log in to receive {"token":"eyJ..."}. GET /api/me with the header Authorization: Bearer eyJ... returns your id and email; without a valid token it returns 401.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which package hashes passwords?

Exercise 2 True / False

The JWT payload is encrypted, so it is safe to store passwords in it.

Exercise 3 Fill in the Blank

Check a token's signature with jwt.___()

Frequently Asked Questions

Because JWTs are stateless, the client simply deletes the token. To invalidate tokens on the server before they expire, keep short expiry times and use refresh tokens stored in the database, which you can delete on logout.