3

I searched for this but I could only find examples in Laravel and PHP, and I need to know how to do this with Next.js.

All I know is that I can do dynamic routes in Next.js the usual way like this ...

/pages/post/[postId] which will translate to /pages/post/23435 for example, and that way if someone has the URL I could just grab the [postId] with router.query and can show the correct post to the user, easy enough.

But what if I want to show the post name in the URL instead of the id? just like what Udemy does with dashes between the words ...

https://www.udemy.com/course/your-custom-react-component/learn/lecture/

And at the same time if someone has that URL I could still show the correct post to them?

I know I could just do /pages/post/[postName] and show the post name in the URL, but that won't be unique, and won't be able to show the correct post.

How can I do that?

Ruby
  • 2,207
  • 12
  • 42
  • 71
  • i think that is a param and you can access it like this router.params.postId for query you would add ?postId=23435 and access it like this router.query.postId – Naveen Kashyap Sep 12 '20 at 10:42
  • @NaveenKashyap I'm not sure I follow, could you post an example? – Ruby Sep 12 '20 at 10:45
  • when someone visit /pages/post/[postId] you can get the postId when component mount or created then make a fetch req with postId – Naveen Kashyap Sep 12 '20 at 11:09
  • @NaveenKashyap No, I know how to do that already, I need to show the post name instead of the id in the URL. – Ruby Sep 12 '20 at 11:43

1 Answers1

1

You can to do it with postName as you propose, and then take care that postNames are unique and that each one maps to a postId (that's something you need to deal with on your side; so in your database you would generate a unique slug for each postName)

Another solution would be to show both the name and the id like /pages/post/[postName]/[postId]. You can use several params, check https://nextjs.org/docs/routing/dynamic-routes

de3
  • 1,890
  • 5
  • 24
  • 39