javascripttypescriptexpressexpress-router

Is there a way to perform regex route parameter matching in Express 5.0.0 after the removal of regex in strings?


Express 5.0.0 contained a number of breaking changes, including the removal of support for RegExp in strings.

Documentation provides guidance to replace RegExps that were used to construct the route patterns, but I cannot find any documentation on type guarding route parameters like you were able to in Express 4.

For example, I have middleware that sets an 'application context' for all requests. It does so if the route follows the pattern /applicationID, where application ID is a UUID.

const applicationContext = Router({ mergeParams: true });

applicationContext.use('/:applicationID([0-9a-f]{8}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{12})',
                       function (req, res, next) {
                           return requireRouteParamsMiddleware([ 'applicationID' ])(req, res, (err) => {
                               if (err) {
                                   return next(err);
                               }
                               return setApplicationContext(req, res, next);
                           });
                       });

How would I be able to achieve the same in Express 5, type guarding the applicationID route parameter to only match upon matching the UUID RegExp pattern?

I tried substituting the string with a new RegExp(...) but quickly realised that (to my knowledge) there was no way to retain the route parameter name in doing so.


Solution

  • This has not actually changed between Express 4 and 5 (tested in v4.21.1 and v5.0.1), but doesn't appear to be explicitly documented on the routing page. You use a named capturing group in the RegExp to turn that into a parameter:

    const express = require("express");
    
    const app = express();
    const port = 3000;
    
    app.get(/\/(?<applicationID>[0-9a-f]{8}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{12})$/, (req, res) => {
      res.json(req.params);
    });
    
    app.listen(port, () => {
      console.info("listening on %d", port);
    });
    
    $ curl http://localhost:3000/abcd1234-ab12-cd34-ef56-abc123def456
    {"applicationID":"abcd1234-ab12-cd34-ef56-abc123def456"}%