How to rewrite url in Express

To rewrite url means to change the requested url (by a web browser, or generally a client) to a different url on the server. Idea is to provide a nicer url to the client, or alter the destination as we need.

Because rewrite url happens on the server, client is not aware of it. Also, client's url remains unchanged (in contrary to redirection that tells client to navigate to a new url, and so url can change).

How rewrite url is done depends on the used server. In Express it is achieved by writing middleware. Below is an example that rewrites /foo to /bar and returns 404 for any other (unknown) address (with a neat trick of returning empty favicon.ico).

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

app.get('/foo', (req, res, next) => {
  req.url = '/bar';
  next();
});

app.get('/bar', (req, res) => {
  res.send('/bar');
});

app.use((req, res) => {
  if (req.url === '/favicon.ico') {
    return res.sendStatus(204);
  }
  res.status(404).send('Not Found!');
});

app.listen(8080);

The order of middlewares matters as they are loaded in the order they are written (from top to bottom).

In Express, middleware is a function with (req, res, next). Route handlers (get, post, put, delete, or all) are middleware functions too.

Resources