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.
npm install express-urlrewriteVerified import paths — ran on the pinned version, not inferred.
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.
Ensure `?` is escaped to `\\?` in regex patterns if it's meant to match the literal character in the URL's query string.
Understand that `app.get(path, rewrite(...), handler)` will effectively execute `rewrite(...)` and then try to match `handler` against the *rewritten* URL as a new route, rather than simply passing control down the current middleware chain. Design your route definitions accordingly.
Upgrade to version 1.1.0 or newer to ensure `req.query` is automatically updated when the rewritten URL includes query parameters. If an upgrade is not possible, manually parse and assign query parameters to `req.query` in a subsequent middleware.
Ensure `express-urlrewrite` is correctly imported and `rewrite` is called with its arguments: `app.use(rewrite('/pattern', '/replacement'))`. For ESM, use `import rewrite from 'express-urlrewrite';`.This is the intended behavior of `express-urlrewrite`. If you require a browser-visible redirect (changing the URL in the address bar), use Express's `res.redirect()` method instead. For example: `app.get('/old-path', (req, res) => res.redirect('/new-path'));`.Escape regex special characters. For example, to match a literal question mark in the URL's path, use `\\?`. To match a literal dot, use `\\.` in your pattern. Test your regex thoroughly.