-3

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

0

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.

brc-dd
  • 10,788
  • 3
  • 47
  • 67
  • But doesn't this make unnecessary requests to the database? If `params.title` was some random string, then makes a request to database to get actual title, checks it against the parameters, redirects to `/blog/123/expected-title`, then again makes a request to database, checks the title, renders page. – Sheikh Ameen Jul 09 '23 at 08:24
  • @SheikhAmeen Implement database caching. You can also do: https://nextjs.org/docs/app/building-your-application/data-fetching/caching – brc-dd Jul 09 '23 at 09:22