node.jsexpressroutes

Multiple optional route parameters in Express?


I am using Express to handle a route which is in the format of /articles/:year/:month/:day, where year, month and day are optional.

My question is, how do I make them optional? With the current route I've defined, unless all three parameters are present, it will not be able to be resolved and will fall into the default route.


Solution

  • The expressjs's guide to routing mentions:

    Express uses path-to-regexp for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths. Express Route Tester is a handy tool for testing basic Express routes, although it does not support pattern matching.

    Basically, you can use the ? character to make the parameter optional.

    /articles/:year?/:month?/:day?
    

    EDIT for ExpressJs 5.x (2024+)

    As from ExpressJs 5.x (2024+) there is a breaking change (as @notx in his answer noted): So the old ? syntax ('/articles/:year?/:month?/:day?') will lead to an error: TypeError: Unexpected ? at ..., expected END: https://git.new/pathToRegexpError

    In express 5.x, braces can be used to define parts of the path that are optional. So, the correct route in express 5.x is: '/articles{/:year}{/:month}{/:day}' (source: https://www.npmjs.com/package/path-to-regexp#optional).