Express URL Rewrite Middleware

2.0.3 · maintenance · verified Wed Apr 22

express-urlrewrite is an Express.js middleware designed for flexible URL rewriting within an application. It allows developers to transform incoming request URLs based on regular expressions, route parameters, or wildcard patterns, without performing HTTP redirects. This is crucial for internal routing, path normalization, or creating cleaner URLs. The library is currently at version 2.0.3 and appears to be in a maintenance phase, with the last publish over two years ago. Its key differentiators include robust support for dynamic rewriting using named or numeric route parameters, wildcards (`*`), and the ability to modify query strings. A notable feature is its capacity to act as route-specific middleware, passing control to the *next matching route* in the Express router rather than the general next middleware in the stack, offering fine-grained control over the request flow.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic Express server and demonstrates three common rewrite patterns: using route parameters, wildcards, and regex with query string handling. It shows how rewritten URLs are then handled by subsequent routes.

import express from 'express';
import rewrite from 'express-urlrewrite';

const app = express();
const PORT = process.env.PORT || 3000;

// Debugging can be enabled via environment variable: DEBUG=express-urlrewrite

// Rewrite /item/123 to /product/123
app.use(rewrite('/item/:id', '/product/:id'));

// Rewrite /legacy-js/vendor/jquery.js to /assets/js/vendor/jquery.js
// Uses wildcard to capture multiple segments
app.use(rewrite('/legacy-js/*', '/assets/js/$1'));

// Rewrite URLs with query string parameter directly into path segment
// Note: The '?' must be escaped in the regular expression
app.use(rewrite('/search\?q=:query', '/results/:query'));

app.get('/product/:id', (req, res) => {
  res.send(`Displaying product ID: ${req.params.id}`);
});

app.get('/assets/js/:path(*)', (req, res) => {
  res.send(`Serving static asset: ${req.params.path}`);
});

app.get('/results/:query', (req, res) => {
  res.send(`Search results for: ${req.params.query}`);
});

app.get('/', (req, res) => {
    res.send('Welcome! Try /item/456, /legacy-js/vendor/library.js, or /search?q=test');
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Try accessing:');
  console.log(`- http://localhost:${PORT}/item/456`);
  console.log(`- http://localhost:${PORT}/legacy-js/vendor/library.js`);
  console.log(`- http://localhost:${PORT}/search?q=example`);
});

view raw JSON →