In NextJs, how do I make a routing system similar to stackoverflow

65 views Asked by At

I want the routes to work in a way that:

  • Visiting www.example.com/blog/12345 should redirect to www.example.com/blog/12345/this-is-a-test.
  • Visiting www.example.com/blog/12345/this-a-some-random-text-blahblahblah should also redirect to www.example.com/blog/12345/this-is-a-test.
  • Visiting www.example.com/blog/12345/this-a-some-random-text-blahblahb/test/having-fun should be 404 error.

The correct blog is always fetched using id, and the title of the blog is set as the second parameter in the URI based on the fetched data.

Right now, for this route: www.example.com/blog/12345/this-is-a-test I have this folder structure in the app/ directory:

app/
  blog/
    [id]/
      [title]/
        page.tsx

From the blog/[id]/[title]/page.tsx file, I have access to both the id and title. Using the id, I can fetch and display some data. No problem, I don't need to use the title. The title is for SEO purposes, and I want to be able to change the title in the URI to the actual title of the resource after being fetched using id.

How do I achieve this? I may have to change the folder structure, but I'm not sure.

1

There are 1 answers

2
brc-dd On

Something like this should work:

import { redirect } from 'next/navigation'

export default function Page({ params }: { params: { id: string; title: string } }) {

  const expectedTitle = getTitleFromId(params.id) // get this from your db or whatever

  if (expectedTitle !== params.title) {
    redirect(`/blog/${params.id}/${expectedTitle}`)
  }

  return <div>My Post: {params.title}</div>
}

Refer: https://nextjs.org/docs/app/api-reference/functions/redirect, https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes

PS: might wanna make title optional if you want to handle example.com/blog/12345 too.