Search code examples
next.js

How to render a single component for every route in Next.js app router?


I want to render one single component for every single route in next.js. I am using the app router in next.js.

The catch all segments route does not work for the index route i.e. the app/[...slug]/page.tsx does not catch the "/" index route. I have to define the app/page.tsx route seperately for it.

Currently I am using a workaround by rendering the same component inside index route page.tsx and the catch all route segment page.tsx file as below:

app/page.tsx:

import CommonComponent from "@/components/common-component";

export default function Page() {
  return <CommonComponent />;
}

app/[...slug]/page.tsx:

import CommonComponent from "@/components/common-component";

export default function Page() {
  return <CommonComponent />;
}

Is there a to define only one route which catches all segments as well as the index page route?


Solution

  • In your case you want to include / in the catch all route, you should use optional catch all route, name your folder [[...slug]] instead of [...slug], if you want more this is the link to the docs: Optional catch all routes