Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js - How to show post name in the url instead of the id and make it unique?

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?

like image 208
Ruby Avatar asked Feb 02 '26 19:02

Ruby


1 Answers

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

like image 93
de3 Avatar answered Feb 04 '26 09:02

de3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!