Search code examples
typescriptgraphqlmetadatadynamically-generatednext.js14

Next 14 Generate Metadata


I recently started learning Next. And I just don’t understand why I can’t have the Id parameter. set to title.

id gets the string.

My Layout is configured correctly.

//src/app/characters/[id]/page.tsx

import graphqlClient from "@/lib/client";
import GET_CHARACTER from "@/lib/graphql/character";
import { CharacterDetail } from "@/components/characters";
import { notFound } from "next/navigation";
import { Metadata } from "next";

type Props = {
  params: {
    id: string;
  };
};
export async function generateMetaData({ params }: Props): Promise<Metadata> {
  const id = params.id;
  console.log(id);
  return { title: id };
}

const CharacterPage = async ({ params }: Props) => {
  try {
    await generateMetaData({ params });
    const { id } = params;
    const {
      data: { character },
    } = await graphqlClient.query<{ character: Character }>({
      query: GET_CHARACTER,
      variables: { id },
    });
    return (
      <div className="container">
        <CharacterDetail character={character} />
      </div>
    );
  } catch (error) {
    return notFound();
  }
};

export default CharacterPage;

My layout. src/app/layout.tsx

import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import React from "react";
import { HeaderLayout, FooterLayout, MainLayout } from "@/components/layout";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: {
    template: "%s | Rick and Morty",
    default: "Rick and Morty",
  },
  description: "Rick and Morty by ortima",
};
interface RootLayoutProps {
  children: React.ReactNode;
}
const RootLayout: React.FC<RootLayoutProps> = ({ children }) => {
  return (
    <html lang="en">
      <body className={inter.className}>
        <HeaderLayout />
        <MainLayout>{children}</MainLayout>
        <FooterLayout />
      </body>
    </html>
  );
};
export default RootLayout;

I tried to use generateStaticParams, but unsuccessfully


Solution

  • generateMetaData is the wrong name, simply change it to generateMetadata

    export async function generateMetadata({ params }: Props): Promise<Metadata> {
      const id = params.id;
      console.log(id);
      return { title: id };
    }