Different Types of Routes

Like mentioned in the part pages, the router of Next.js is based on the file-system. This means that adding a file to the pages directory makes it automatically available as a route.

Different Types of Routes

  1. Index Routes

    • Automatically makes index file name the root of the directory.

    • pages/index.js —> /

    • pages/blog/index.js —> /blog

  2. Nested Routes

    • Router supports nested files.

    • Will still be routed the same way.

    • pages/blog/first-post.js —> /blog/first-post.js

    • pages/dashboard/settings/username.js —> /dashboard/settings/username.

  3. Dynamic Routing Segments

    • You can use the bracket syntax when trying to match a dynamic segment.

    • This allows you to match named parameters.

      • pages/blog/[slug].js —> /blog/:slug (/blog/hello-world)

      • pages/[username]/settings.js —> /:username/settings (/foo/settings)

      • pages/post/[...all].js —> /post/* (/post/2020/id/title)

Linking to Dynamic Paths

When creating dynamic route segments, it can be very useful to use interpolation in a path name.

<Link href={`/blog/${encodeURIComponent(post.slug)}`}>

You can also, instead, use a URL Object:

<Link href={{pathname: '/blog/[slug]',query: { slug: post.slug },}}>

The URL Object can be used instead of using interpolation to create a path.

  • Pathname is the name of the page in the pages directory.

  • Query is an object with the dynamic segment, which is slug in this case.

Injecting the Router

You can access the router object in a React component by using either useRouter or withRouter, recommended is the first type.