Search code examples
next.jsroutesapp-routernext-routergetstaticprops

How to create custom routes using Next.js's App router?


I have been using App router because it was recommended at the time of project init. I want a custom route for example base_url/products/product-slug. It is pretty simple using page router, we can have a a file named [slug].js under page/products. But can this be implemented using App router?

I have created a file [slug].js under app/shop. I would like a custom route. So if I go to /shop/product-slug, it should render whatever is in /app/shop/products/index.js file

app/
|-- shop/
|   |-- page.js
|   |-- layout.js
|   |-- products/
|   |   |-- [slug].js
|-- dashboard/
|   |   |-- page.js

I have tried having page.js file in products directory but it does not work for dynamic data.


Solution

  • You probably mean a Dynamic route, not a custom route. If that's the case, In Next.js App router it's a bit different than pages, in App router, the routes are the folder names not the file names.

    For your case, inside shop folder you should create a folder named [slug], inside this folder there should be page.tsx file which will be displayed when you navigate to base_url/shop/products/1 for example.

    You can learn more about Dynamic route in Next.js App Router