#Dynamic routes

1 messages · Page 1 of 1 (latest)

fossil python
#

I have the following project structure:
/account/page.tsx
/account/trips/[id]/page.tsx

I would like the content from /account to display when the user tries to load /account/trips.

What is the best practice to achieve this?

heady scaffoldBOT
#

Hi @fossil python. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To display the content from /account when a user tries to load /account/trips, you have a few options in Next.js. Based on the knowledge sources, here's how you can achieve this:

Option 1: Create a catch-all route

You can create an optional catch-all route in the /account directory that will handle both /account and /account/trips:

  1. Create a file structure like this:
/account/[[...slug]]/page.tsx

This optional catch-all segment will match both /account (where slug would be undefined) and /account/trips (where slug would be ['trips']).

Dynamic Routes documentation explains that optional catch-all segments can match the route without the parameter as well as routes with parameters.

Option 2: Create a specific route for /account/trips

You can create a specific route for /account/trips that reuses the content from /account:

/account/trips/page.tsx

In this file, you can import and render the same component that's used in /account/page.tsx.

Option 3: Use a layout

You could also use a layout to share UI between these routes:

  1. Create a layout file in the account directory:
/account/layout.tsx
  1. In this layout, you can conditionally render the content from /account/page.tsx when the path is /account/trips.

Layouts and Pages documentation shows how layouts can be used to share UI between routes.

Best Practice

The most Next.js-idiomatic approach would be Option 1 with the optional catch-all route, as it leverages Next.js's routing system directly. This approach is clean and follows the framework's conventions for handling multiple route patterns with the same content.

#

If you need more specific control or have more complex requirements, Option 3 with layouts might be more appropriate, especially if you need to share UI between multiple routes under /account.

Remember that with any of these approaches, you'll need to handle the navigation between these routes appropriately using the <Link> component or the useRouter hook.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: