next.jsurl-routing

2 Level of dynamic routing in next.js


I am new to next.js. I want to ask how to achieve two level of dynamic routing in next.js?

My url is http://localhost:3000/company/[slug1]/[slug2]

In the next.js official documentation I got only one level nesting routing.

I want to 2 level routing.


Solution

  • Create directory structure like this

    pages/
     └─ company/
         └─ [slug1]/
             └─ [slug2].js
    

    To access segments on the client side

    import { useRouter } from 'next/router';
    
    export function Component() {
      const router = useRouter();
      const { slug1, slug2 } = router.query;
      // ...
    }
    
    

    Or if on the server side

    export async function getServerSideProps(ctx) {
      const { slug1, slug2 } = ctx.params;
      // ...
    }