How to use route matching for serverless functions?

I am building a serverless REST API with Netlify, which will eventually fetch data from a database. However, when testing locally, I came across an issue: there’s no “easy” way to match a specific function for a specific route.

For example, I have a generic function to list all users that executes whenever /users/ is accessed. Then, I want to use another function if I access /users/:id, and I want to be able to retrieve this id from the path.

I know it’s possible with express or other frameworks, but is it possible to do without any external framework other than Netlify?

I managed to retrieve the route param by using feather-route-matcher, but I have to implement it in every function, which brings me to another question: is it possible to use it as a middleware, to return the parameters in the path?

1 Like

Hi @Xinayder,

If I have understood the question correctly, you can always use query string parameters.

For example, the redirect rule could be like: /users/?id=123 and then, in the function you could do something like:

exports.handler = async event => {
  const id = event.queryStringParameters.id
  return {
    //
  }
}

Hi Hrishikesh,

Thanks for sharing the info about the query string parameters. But I’d just like to know if params (products/123) or hash (products/#123) values can be retrieved from the url in netlify serverless functions.

I have an existing application that uses the hash value and was wondering if I could use it as is…

Hash values are only used by browsers in client-side and are not transferred to a server. So that would not work, at least not out of the box.

1 Like