I'm fairly new to nextjs 13, especially with the app router, I have a very big project in react that I would like to migrate and I know it won't be an easy road, I've started to tackle a bit of the future challenges, starting with routing.
I will have a lot of routes, but for now let's focus on one, we will call it "section", and the path will be something like : /:section?/:subsection?
Routing with nextjs has always been kind of mystical to me, I know react-router really well but not the folder logic by the nextjs team.
I know typical routing in nextjs is folder directed, like app/section/page.tsx, app/about/[id] etc
Thing is, I don't know these things in my case, because they are fully dynamical, I've searched in the nextjs doc but could not find an easy answer.
My ideal project folder will be something like src/app/section/page.tsx, src/app/post/page.tsx, etc
I have gone the path of rewrites, in the next-config.js file, but I can't make it work.
I can retrieve the query params in the main page, through the props given by nextjs, but I can't retrieve it in a client component through any of the hooks.
I have done a codesanbox of course, to give you a reproducing code.
To reproduce, navigate to an url like /one/two, and look at both the browser and node console.
The repo: https://codesandbox.io/p/sandbox/brave-dew-sh75dc
Everything in the description
Next.js uses file-based router. Here are some solution for your routing cases in the question and the comments:
To make a dynamic route, you can use
[slug]format in folder name. It can be nested at any level of nesting. You can makesrc/app/[section]/[subscription]/page.tsxYou can then read the
sectionandsubscriptionvalues in page.js (as well as layout.js) via the props:Or in Client Components via
useParamshook:You can also, use
useSelectedLayoutSegmentanduseSelectedLayoutSegmentsin Client Components under layout.To read the query params e.g.
?id=123in a page.js you can use the propsearchParamsOr using
useSearchParamsin ClientComponents:To implement
/:section/:subsection/:slug(.*)-id([0-9]*)You could makesrc/app/[section]/[subscription]/[slug]/page.jswith Self-healing URL.This Blog explains Self-healing URLs very well: