Next.js Discord

Discord Forum

How to handle possibly undefined dynamic routes on root using the same page.tsx file

Answered
jsoneaday posted this in #help-forum
Open in Discord
I am using the App Router with nextjs 15. I have a route with a path like this
http://myapp.com/
Sometimes the root of my app will have a parameter, id, sometimes it will not. How can I use the same page.tsx file to handle both param cases even though I am on the root of my app.
Answered by Clown
You can also use optional catch-all segments if you do a bit of validation(at most 1 route segment instead of 0 or more):
https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes#optional-catch-all-segments
View full answer

4 Replies

the 2 ways on the top of my mind would be
1. use nextjs rewrites to rewrite / to /home (or smth)
2. make app/page.tsx just import and export from app/[dynamic]/page.tsx]
You can also use optional catch-all segments if you do a bit of validation(at most 1 route segment instead of 0 or more):
https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes#optional-catch-all-segments
Answer
You are legit. Thanks