javascriptreactjsnext.jsnested-routesnext-router

Dynamic nested routes in Next.js


I am building an e-commerce web app in Next.js and I got stuck on product filtering. Let's say there are 3 possible filtering options:

  1. by category - dioptric / sunglasses
  2. by sex - men / women
  3. by brand - rayban / gucci

Now, the filters should work as subpages. Let's say the user chose sunglasses for men, so the URL should look like this: /sunglasses/men. Now, here are 4 possible example URLs on my website:

  1. /sunglasses/men
  2. /sunglasses/rayban
  3. /sunglasses/men/rayban
  4. /sunglasses/rayban/men

I cannot figure out how the router should be able to distinguish between the first two URLs and figure out that the second parameter in the first URL is a sex filter, but the second parameter in the second URL is a brand filter.

I am using Next.js and its server side rendering (getServerSideProps).

Thank you for any help.


Solution

  • You can use the spread operator inside the route name to solve this problem.

    #  pages/[...product].ts
    

    Example: pages/sunglasses/men/gucci

    Your query object will be like this

    {"product": ["sunglasses","men","gucci"]}
    

    More information check Nextjs Docs