Multiple optional route parameters in Express?

CLDev picture CLDev · Jan 19, 2017 · Viewed 51.5k times · Source

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.

  • If none of the three params is given, all articles will be returned;
  • If year is given, articles of that year will be returned;
  • If year and month are given, articles of that year and month will be returned;
  • If all three params are given, articles of that year, month and day will be returned.

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.

Answer

hjpotter92 picture hjpotter92 · Jan 19, 2017

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?