1

I've looked around Stackoverflow and the general consensus seems to be adding to my server file.

Though I'm wondering if this is possible with NextJS's dynamic routing.

I'm trying to achieving a route that looks something like this:

/categories/:id/articles/:id

I've tried doing something like this

- pages
  - categories
    - [id]
      - :id.js
      - articles
        - :id.js

To no avail, so perhaps this wasn't the best approach. Would I be able to achieve something like this without touching the server?

1 Answer 1

10

Yes it can be done. You need to create a structure in your pages directory like this.

- pages
  - categories
    - [categoryId]
      - articles
        - [articleId].js

In [articleId].js you will have access to params.categoryId and params.articleId.

If you want to show an article list page for /categories/:categoryId/articles you can achieve that by creating a index.js file in the articles folder. Similarly if you want to show a list of categories you can create an index.js file in categories folder For example,

- pages
  - categories
    - index.js   // to show a list of categories
    - [categoryId]
      - articles
        - index.js // to show list of articles for a specific category
        - [articleId].js

To summarize

  • /categories will show NextPage component in pages/categories/index.js.
  • /categories/:categoryId/articles will show NextPage component in pages/categories/[categoryId]/articles/index.js
  • categories/:categoryId/articles/:articlesId will show the NextPage component in pages/categories/[categoryId]/articles/[articleId].js
Sign up to request clarification or add additional context in comments.

5 Comments

Awesome!! Because I had my routes in a :id format, the only thing I had to do is change the directory from [id] to :id and it works. Thank you!
please what version of Nexjs are you guys using? It doesn't work for me. I get a 404.
@Sofiane That's the core routing logic and to my knowledge should work in any version of next, unless you are working with a very old version which had some issues with routing at some point. Please consider posting a question with detailed information, so someone may be able to help with the issue you are having in your case.
@Sofiane I tried everything and had the same issue, but then I realized I didn't add import { useRouter } from 'next/router'; in those new pages. Check this example repo for all the folder and code stuff: github.com/vercel/next.js/tree/canary/examples/dynamic-routing
@subashMahapatra So If you have index.js inside [categoryId], will that serve categories/:categoryId/ ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.