🎓 A1Learner
🔍
0 of 50 lessons completed

Protecting Routes

A protected route is a route that needs a valid token. It turns away requests that carry no token or a bad token.

The token check

The check reads the token and checks its signature.

function checkToken(req, res, next) {
  const header = req.headers.authorization || '';
  const token = header.replace('Bearer ', '');
  try { req.user = jwt.verify(token, 'dev-secret'); next(); }
  catch { res.status(401).json({ error: 'Token missing' }); }
}

Guarding the notes route

The check runs before the route handler.

app.get('/api/notes', checkToken, (req, res) => {
  res.json([{ title: 'Buy milk', done: false }]);
});

Example

import express from 'express';
import jwt from 'jsonwebtoken';

const secret = 'dev-secret';
const app = express();
app.use(express.json());

function checkToken(req, res, next) {
  const header = req.headers.authorization || '';
  const token = header.replace('Bearer ', '');
  try {
    req.user = jwt.verify(token, secret);
    next();
  } catch {
    res.status(401).json({ error: 'Token missing' });
  }
}

app.post('/api/login', (req, res) => {
  const token = jwt.sign({ username: 'ana' }, secret);
  res.json({ token });
});

app.get('/api/notes', checkToken, (req, res) => {
  res.json([{ title: 'Buy milk', done: false }]);
});

const server = app.listen(0, async () => {
  const base = 'http://localhost:' + server.address().port;
  const noToken = await fetch(base + '/api/notes');
  console.log(noToken.status + ' ' + await noToken.text());
  const login = await fetch(base + '/api/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username: 'ana' })
  });
  const data = await login.json();
  const withToken = await fetch(base + '/api/notes', {
    headers: { Authorization: 'Bearer ' + data.token }
  });
  console.log(withToken.status + ' ' + await withToken.text());
  server.close();
});

Key points

  • A middleware function is a check that runs before a route.
  • A header is a small labelled value sent with a request.
  • The token travels in the Authorization header of the request.
  • A request with no token gets a 401 answer.
  • A request with a good token reaches the notes.

In this example, the app has a login route and a guarded notes route. The script first fetches the notes with no token. It then logs in and fetches the notes again with the token. The two printed lines show the refused request and the allowed one.

Note

The check runs on every protected route, not just one.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens to a request with no token on a protected route?