If you want to use regex for an Express.js route rule then you must use a JS regular expression object instead if string by wrapping your regular expression in slashes (/
) instead of quotes ("
). To look at a common usage example, let’s say you want the same route handler for two different root paths in your app, like /rest/*
and /api/*
.
String Routing Rules
Express uses path-to-regexp to simplify the process of writing routing rules. path-to-regex
is what turns rules like /order/:id
or /post/:id
into a RegEx pattern for matching.
// String route rules
var handler = function( req, res, next ) {
res.send( "My route worked!" );
};
app.get( '/api/:param', handler );
app.get( '/rest/:param', handler );
Regex Rules for Parameters
Express.js provides a way to use a custom regex rule for a specific parameter in a route. Let’s say we wanted a :userId
parameter in a route rule to match only a 6 digit integer. The following regex parameter rule does that well.
// Regex rule for route parameter
app.get( '^/users/:userId([0-9]{6})', function( req, res ) {
res.send( 'Route match for User ID: ' + req.params.userId );
} );
Pure Regex Routing Rules
If you want to use a pure regex for an Express.js route rule then you must use a JS regular expression object instead if string by wrapping your regular expression in slashes (/
) instead of quotes ("
).
// Regex route rule
app.get( /^\/(api|rest)\/.+$/, function( req, res, next ) {
res.send( "My route worked!" );
} );
Helpful Tools
If you’re writing custom regex routing rules for Express.js then I highly suggest the following useful tools:
- Express Route Tester — A great utility that you can use to test out how Express routes are translated to regex rules
- Regex101 — A great resource for creating, testing, and understanding regular expressions
- Express.js Routing Docs — Be sure to reference these for basics on Express.js routing