0
0
Expressframework~5 mins

JWT token verification middleware in Express

Choose your learning style9 modes available
Introduction

JWT token verification middleware checks if a user is allowed to access certain parts of a web app by confirming their token is valid.

When you want to protect routes so only logged-in users can access them.
When you need to check user identity before allowing actions like posting or deleting data.
When you want to make sure the token sent by the user is not expired or tampered with.
When building APIs that require secure access control.
When you want to add a simple way to verify users without storing session data on the server.
Syntax
Express
const jwt = require('jsonwebtoken');

function verifyToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  if (!authHeader) {
    return res.status(401).send('Access denied. No token provided.');
  }
  const token = authHeader.split(' ')[1];
  if (!token) {
    return res.status(401).send('Access denied. Token missing.');
  }
  try {
    const decoded = jwt.verify(token, 'your-secret-key');
    req.user = decoded;
    next();
  } catch (err) {
    res.status(400).send('Invalid token.');
  }
}

The middleware reads the token from the Authorization header.

Use jwt.verify() to check if the token is valid and not expired.

Examples
Get the token from the request headers.
Express
const authHeader = req.headers['authorization'];
const token = authHeader.split(' ')[1];
Verify the token using your secret key and get the decoded user info.
Express
const decoded = jwt.verify(token, 'your-secret-key');
Attach the decoded data to the request and call next() to continue.
Express
req.user = decoded;
next();
Sample Program

This Express app has three routes:

  • /public: anyone can access.
  • /login: simulates login and returns a JWT token.
  • /protected: only accessible if a valid JWT token is sent in the Authorization header.

The verifyToken middleware checks the token before allowing access to the protected route.

Express
const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
const PORT = 3000;
const SECRET_KEY = 'mysecretkey';

// Middleware to verify JWT token
function verifyToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  if (!authHeader) {
    return res.status(401).send('Access denied. No token provided.');
  }
  const token = authHeader.split(' ')[1]; // Expecting 'Bearer <token>'
  if (!token) {
    return res.status(401).send('Access denied. Token missing.');
  }
  try {
    const decoded = jwt.verify(token, SECRET_KEY);
    req.user = decoded;
    next();
  } catch (err) {
    res.status(400).send('Invalid token.');
  }
}

// Public route
app.get('/public', (req, res) => {
  res.send('This is a public route.');
});

// Protected route
app.get('/protected', verifyToken, (req, res) => {
  res.send(`Welcome ${req.user.name}, you accessed a protected route!`);
});

// Route to get a token (simulate login)
app.get('/login', (req, res) => {
  // Normally, you'd check user credentials here
  const user = { id: 1, name: 'Alice' };
  const token = jwt.sign(user, SECRET_KEY, { expiresIn: '1h' });
  res.json({ token });
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
OutputSuccess
Important Notes

Always keep your secret key safe and never share it publicly.

The token is usually sent in the header as Authorization: Bearer <token>.

Use HTTPS to keep tokens secure during transmission.

Summary

JWT middleware checks if a token is valid before allowing access.

It protects routes by verifying user identity without sessions.

Tokens are sent in the Authorization header and verified with a secret key.