![]() |
VOOZH | about |
Dynamic routing is a core feature in modern web frameworks, enabling applications to handle variable paths based on user input or dynamic content. In Next.js 13+, with the introduction of the App Router, dynamic routes are implemented using a folder-based structure inside the app directory.
This article provides a step-by-step guide to implementing dynamic routes using the latest App Router approach, replacing the legacy pages directory system.
Dynamic route segments allow developers to define routes that adapt to variable content. For instance, a blog platform might use URLs like /post/123 or /post/my-article. The segment (123, my-article) is dynamic and handled by bracket syntax:
app/post/[id]/page.jsWith this structure, any value in place of [id] is captured and made available via the routing API.
Here is a step-by-step guide to creating the routing:
Use the following command to bootstrap your project:
npx create-next-app@latest gfgDuring setup, ensure you select the following options:
Inside the app directory, create a nested folder structure for your route:
app/
route/
[data]/
page.jsUse the useParams() hook provided by next/navigation to access the dynamic value:
In the above example first, we are calling our useRouter() hook and after that, we are displaying the objects of our router in the console.
Launch your app using:
npm run devVisit a route like http://localhost:3000/route/hello, and you'll see:
Output: