NEXT JS: Routing

PART IV

NEXT JS: Routing

ROUTE

Next.js uses a file-system based router where folders are used to define routes.

New folder in app directory === Means route

A special page.js file is used to make route segments publicly accessible.

In this example, the /dashboard/analytics URL path is not publicly accessible because it does not have a corresponding page.js file. This folder could be used to store components, stylesheets, images, or other colocated files.

Defining Routes

Nested Routing

Nested folder in app directory

  • app/blog/first-post/page.js/blog/first-post

  • app/dashboard/settings/username/page.js/dashboard/settings/username

Dynamic Routing

  • app/posts/[postId]/posts/12341

      // PAGE.TSX
      import React from 'react'
    
      const page = () => {
        return (
          <div>{postId}</div>
        )
      }
    
      export default page
    

Route Group

To organize routes without affecting the URL, create a group to keep related routes together.

This allows you to organize your route segments and project files into logical groups without affecting the URL path structure.

Route groups are useful for:

Organizing Routes with Route Groups

  • The naming of route groups has no special significance other than for organization. They do not affect the URL path.

  • Routes that include a route group should not resolve to the same URL path as other routes. For example, since route groups don't affect URL structure, (marketing)/about/page.js and (shop)/about/page.js would both resolve to /about and cause an error.

  • If you use multiple root layouts without a top-level layout.js file, your home page.js file should be defined in one of the route groups, For example: app/(marketing)/page.js.

  • Navigating across multiple root layouts will cause a full page load (as opposed to a client-side navigation). For example, navigating from /cart that uses app/(shop)/layout.js to /blog that uses app/(marketing)/layout.js will cause a full page load. This only applies to multiple root layouts.

Creating multiple root layouts

To create multiple root layouts, remove the top-level layout.js file, and add a layout.js file inside each route groups. This is useful for partitioning an application into sections that have a completely different UI or experience. The <html> and <body> tags need to be added to each root layout.

Route Groups with Multiple Root Layouts

Colocation

In addition to special files, you have the option to colocate your own files (e.g. components, styles, tests, etc) inside folders in the app directory.

This is because while folders define routes, only the contents returned by page.js or route.js are publicly addressable.

An example folder structure with colocated files

REFERENCE