Adding dynamic URLs to the canonical tags in Next.js version 14.2.4: A comprehensive guide

I'm currently facing an issue with implementing dynamic URLs in my Next.js dynamic routes.

To generate metadata, I am utilizing a server-rendered page:

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 specific dynamic page that requires SEO optimization is shown in the image below:

https://i.sstatic.net/oifof2A4.png

My challenge lies in implementing this for dynamic pages as opposed to static pages, where I can't use hooks to retrieve the pathname on server-rendered pages.

What steps should I take next to address this issue?

Answer №1

If you want to enhance your dynamic page, consider adding the following code snippet at the top:

import type { Metadata, ResolvingMetadata } from 'next'

type Props = {
   params: { slug: string }
   searchParams: { [key: string]: string | string[] | undefined }
 }

 export async function generateAdditionalData(
  { params, searchParams }: Props,
    parent: ResolvingMetadata
   ): Promise<Metadata> {
  // extract parameters from the route
   const slug = params.slug

 // fetch data or use a local JSON file
 const product = await fetch(`https://.../${slug}`).then((res) => res.json())


return {
   title: product.title,
 }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Nestjs struggles with resolving dependencies

Having trouble finding the issue in my code. (I'm still new to nestjs and trying to learn by working on some apps). The console log is showing the following error: Nest can't resolve dependencies of the UrlsAfipService (?). Please ensure tha ...

Utilizing the moment function within an Angular application

I've successfully added the library moment.js by running: npm i moment I've included it in scripts and attempted to import it in module.ts. However, when I try to use moment in component.ts, I'm getting an error that says: 'canno ...

Expo project encountering issues with nested navigation in React-Native

When configuring the header in my app using React Native Stack Navigation and nesting a Drawer Navigation inside of it, I encountered a strange issue. While everything worked fine in the android emulator, opening the app using Expo resulted in nothing but ...

Testing Next.js's getServerSideProps function with Jest: A Step-by-Step Guide

I want to conduct Jest and Enzyme tests on the Next.js getServerSideProps function. This function is structured as follows: export const getServerSideProps: GetServerSideProps = async (context) => { const id = context?.params?.id; const businessName ...

Passing a parameter from a redirect function to an onClick in React using TypeScript

I am facing a challenge in passing a parameter to my redirectSingleLocker function. This function is intended to take me to the detailed page of a specific locker, identified by a guid. The lockerData.map method is used to display all the JSON data in a ta ...

Next.js page freezes when Axios request is made causing the tab to become unresponsive

Curious about how to troubleshoot (or where to start) with my current Axios problem. I am working on a Next.js project (12.3) and have an axios interceptor hook that manages all of my internal requests. The interceptor functions properly on every action/pa ...

Implementing Google Fonts with Tailwind CSS in a Next.js Project

Struggling to integrate Google Font with Tailwind CSS in my Next.js project. Can anyone help? ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

Guide for Showing Data from Json Mapper in Angular 5

As a newcomer to Angular5 with TypeScript, I am trying to figure out how to display data from my JSON. I have an API that was created using Java. I have created a JSON Mapper in my Angular code like this : The JSON generated from my Java application looks ...

The issue of assigning a file as a prop in React TypeScript: ("True" type cannot be assigned to "ChangeEventHandler<HTMLInputElement>")

I'm currently developing an application using reactjs My goal is to implement a feature that allows file uploads passed as a prop from a child component to a parent component Child Component const RegisterIndividual: React.FC< { upload_id_card: R ...

The ngx-mat-intl-tel-input plugin is experiencing issues with functionality within the Angular 17 framework

I am currently using Angular 17 and here are the specific Versions/Details: Angular CLI: 17.3.8 Node: 18.20.2 Package Manager: npm 10.5.0 OS: linux x64 Angular: 17.3.12 My goal is to import the ngx-intl-tel-input library in order to validate phone numbers ...

What is the best way to refresh the snapshots in my React/TypeScript project?

I am working on a React/TypeScript project that utilizes the Jest testing framework. Occasionally, after making changes to my code, Jest will compare it to the snapshots and generate an alert requesting me to update them. However, there are instances where ...

What is causing the TypeError in next-auth when attempting to destructure the 'manager' property of the 'connection' object, which is null?

I encountered an error when connecting to mongo atlas, but everything works fine with a local database. Please refer to the image of the db connection and the terminal error for additional details. dbconnect.ts import mongoose from "mongoose"; ...

Exploring opportunities to earn revenue from a website created with Next Js through Adsterra

I've been exploring options to monetize my Next Js website using Adsterra. However, I encountered an issue when trying to implement the Google Adsense code specifically designed for Next js. Should the code be placed within _document.js? <scrip ...

Issue with Variable Passing Correctly to Form

Can someone help me figure out how to update the value of textbox retentionx with '0OTHXXGK1DCA19JUN-thank you'? Currently, the text in the textbox is only displaying '0OTHXXGK1DCA19JUN-thank' and isn't fully visible. Code snippet ...

The i18next-http-backend module could not be loaded

After implementing the code below to create the module 'i18next-http-backend' (installed version: "i18next-http-backend": "^1.4.1"), I encountered an issue where the module cannot be loaded. The browser console displayed the e ...

Challenging Issue: "The 'any' type cannot be assigned to the 'never' type"

Currently facing a challenging Typescript problem that has me puzzled. The issue arises at the line themeToChange[tileId][key] = value; The error message states Type 'any' is not assignable to type 'never' This error is directly rela ...

Having trouble setting State in React with Typescript?

I have encountered an issue with merging strings in an array. Despite successfully joining two strings and logging the result using console.log('Dates: ' + mergedActions), the merged string doesn't seem to be set in this.state.MergedAllActio ...

Testing a NestJS service with multiple constructor parameters can be done by utilizing various techniques such as dependency

Content When testing a service that needs one parameter in the constructor, it's essential to initialize the service as a provider using an object instead of directly passing the service through: auth.service.ts (example) @Injectable() export class ...

Generate an observable by utilizing a component method which is triggered as an event handler

My current component setup looks like this: @Component({ template: ` ... <child-component (childEvent)="onChildEvent()"></child-component> ` }) export class ParentComponent { onChildEvent() { ... } } I am aiming to ...