Express app.get ending with "?". Is that regex?

In Timestamp Microservice project, the endpoint is GET [project_url]/api/timestamp/:date_string?


app.get("/api/timestamp/:date_string?", otherCode)

Without the “?” I couldn’t check for empty parameters on /api/timestamp !


? is conventionally used as a separator for the query string, example,


can have the query string (‘hello’) parsed in express with req.query.message.

Also take a closer look at this exercise:

I understand that it usually is used to separate the query string, but if you try to make the api without that at the end then it doesn’t work. The API examples that give only use req.params not req.query

Here is my code:

app.get("/api/timestamp/:date_string?", (req, res) => {
  let str = req.params.date_string
  if (str == undefined) {
    let date = new Date()
    res.json({ unix: date.getTime(), utc: date.toUTCString() })
  } else if (typeof str == 'string') {
    if (Number.isInteger(Number(str))) {
        let date = new Date(Number(str));
          unix: date.getTime(),
          utc: date.toUTCString()
    } else if (new Date(str) != "Invalid Date") {
      let date = new Date(str);
        unix: date.getTime(),
        utc: date.toUTCString()
    } else {
      res.json({ error: "Invalid Date" })   

If you don’t have the “?” at the end of GET url, you will get “Cannot GET /api/timestamp” if you don’t append “/someDateFormatHere”

I see what you are asking now, if get route is /api/timestamp/:date_string and request is .../api/timestamp then req.params holds no value at all since the route parameter is empty and hence you receive a Cannot GET... , however if get route is this /api/timestamp/:date_string? then req.params holds the following value { date_string: undefined } for the same request since ‘?’ acts as a place holder for an empty route parameter as it is not recognized as a word character (a requirement for express route parameters) but at the same time express recognizes ‘?’ as ‘subsets of their regular expression counterparts’ in routes.

Good question any how.

So does “?” make Express think there will be query string so :date_string must exist (be undefined if there isn’t anything) or is it using it as a regex?

1 Like

In the doc I linked above it says

Express uses path-to-regexp for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths.

If you go to the path-to-regexp documentation it says under Parameter Modifiers,

Parameters can be suffixed with a question mark ( ? ) to make the parameter optional.

So if adding the ‘?’ makes the route parameter optional, then an empty request without the ‘?’ means that it is not a route that express can even match, and so the handler function is not even called.