node.jstypescriptexpressnestjsfastify

how to use optional url parameters with NestjS


I'm trying to replace our current backend service using Nestjs library, however, I want to create a route with 2 optional parameters in the URL something like :

/route/:param1/config/:OptionalParam3?/:OptionalParam3?

that means the route should catch :

  1. route/aa/config
  2. route/aa/config/bb
  3. route/aa/config/bb/cc

how can I achieve that, I have tried to use ? and () but it's not working well.


Solution

  • Router params name should be unique. The correct route path is:

    Existing one is:

    /route/:param1/config/:OptionalParam3?/:OptionalParam3?
    

    Correction:

    /route/:param1/config/:OptionalParam3?/:OptionalParam4?
    

    Opinion: You can use query params if the params are optional. It is never a good idea to create optional param routes (disagreements agreed). Both serve the same purpose, but having them as the query params makes it more understandable for debugging and fellow developers.