4

tl;dr: I need mypage.com/users/123 to behave like mypage.com/users?user_id=123

I'm using Next.js 10. I'd like to have routes like mypage.com/users/123 and mypage.com/users/445. All my searches take me to dynamic routing, which suggests using this structure under the pages folder:

users/
   [user_id].js

This doesn't work for my case, because then a new page is generated in the server for every user. I only want one page, statically generated, under users/, that gets the user_id as a parameter on the client side.

With query params, this is straightforward. I can use this folder structure

users/
   index.js

and then, when someone goes to mypage.com/users?user_id=123, the same page gets served, and then client side js code can access the user_id.

Possible solution

My current solution (which I find too intricate, but may help someone) is adding a rewrite on next.config.js, like this:

module.exports = {
  rewrites() {
    return [{ source: '/users/:user_id', destination: '/users?user_id=:user_id' }];
  }
}
jordiburgos
  • 5,964
  • 4
  • 46
  • 80
LGenzelis
  • 764
  • 6
  • 14

0 Answers0