How to correctly handle SSG pagination with dynamic routes in Next.js?

Viewed 25

I'm fairly new to Next as a framework and I'm trying to determine how best to handle pagination. My goal is to have urls such as:

  • /category-one
  • /category-one/2
  • /category-one/3
  • /category-two
  • /category-two/2
  • ... and so on

*notice the lack of a /1

Next appears to operate through dynamic slugs in the folder/filename e.g.

pages/  
  [category]/  
    [page].jsx  

However, what I'm struggling to work out, is that how I can have a page template for NON-paginated urls, and one for paginated urls, without essentially copying the file, this ending up with a bunch of extra code to maintain.

My first thought was to see if I could have say:

pages/
  [page].jsx  
  [category]/  
    [page].jsx  

and extend the parent page for the child page, and just add some littles bits to handle the second part of the slug.

However, this doesn't seem to be an option. I feel like I'm missing something obvious, but I can't seem to find any examples that show a similar setup to what I'm seeking.

I appreciate that the simple answer would be "just have a /1 after the page one and forget the parent page template altogether", but I'd expect that a framework as robust as Next.js would be able to handle something simple like this.

Any help/pointers would be greatly appreciated!

1 Answers

For anybody finding this question and having the same problem, the answer (which was provided by juliomalves in the comments) is exactly what was missing.

Look into optional catch-all routes.

Related