Search code examples
typescriptnext.jsseonext.js14

How to add dynamic url to canonical tag in Next.js 14.2.4


I am trying to add dynamic url to my Next.js dynamic routes.

I am using server rendered page to generate metadata:

export const metadata: Metadata = {
   title: `InterviewQA |  ItsIndianGuy`,
   description:
      "Explore interview questions in various programming languages such as JavaScript, Python, C++ and more. Enhance your preparation with comprehensive language-specific content.",
   alternates: {
      canonical: "https://itsindianguy.in/interview-qa",
   },
};

The dynamic page i want to add seo for is in pic

Folder structure

Now the problem is, I have added it to static pages, but when it comes to dynamic pages, how do I add it?

Because I can't use hooks to get the pathname in Server rendered pages.

What can I try next?


Solution

  • You can add this at the top your your dynamic page:

    import type { Metadata, ResolvingMetadata } from 'next'
    
    type Props = {
       params: { slug: string }
       searchParams: { [key: string]: string | string[] | undefined }
     }
    
     export async function generateMetadata(
      { params, searchParams }: Props,
        parent: ResolvingMetadata
       ): Promise<Metadata> {
      // read route params
       const slug = params.slug
    
     // fetch data or use local json data
     const product = await fetch(`https://.../${slug}`).then((res) => res.json())
    
    
    return {
       title: product.title,
     }
    }