Adding a Page Title
Overview
The page title is the text that appears in the browser tab. It is also used by search engines to determine the content of the page. It is important to have a unique page title for each page.
[Server Component] -Changing page title from a dynamic page
To change the page title from a dynamic page, you can use the generateMetadata
function to update the page title. Here's an example:
type GenerateMetaDataProps = {
params: { quoteId: string };
searchParams?: { [key: string]: string | string[] | undefined };
};
export async function generateMetadata({ params }: GenerateMetaDataProps) {
// call some api / method to fetch dynamic content
const product = await getProduct();
return {
title: `Product - ${product.id}`,
};
}
This will update the page title to "Page Title" when the component loaded on the server. Consider the following example where we are fetching the single quote using an api and updating the document title. Example:
import QuoteContainer from "@/app/containers/quotes/view/quote-container";
import { getQuoteDetail } from "@/app/actions/quotes";
type GenerateMetaDataProps = {
params: { quoteId: string },
searchParams?: { [key: string]: string | string[] | undefined },
};
export async function generateMetadata({ params }: GenerateMetaDataProps) {
const quote = await getQuoteDetail(params.quoteId);
return {
title: `${quote.id} / ${quote.name} / ${quote.status.description} | ${quote.vendor.displayName} - Zeus Commercial Product`,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const ViewQuote = async ({ params }: { params: Record<string, any> }) => {
await getQuoteDetail(params.quoteId);
return <QuoteContainer />;
};
export default ViewQuote;
Here you can notice that we are using a getQuoteDetail
function which will return us the single quote details and we are returning an object with title
property, which will set the document title automatically when the page loads on your browser automatically.
For better coding structure we can put the getQuoteDetail
as a server action in path app/actions
. Consider the following example of the getQuoteDetail
server action in path `app/actions/quotes.ts.
"use server";
import { redirect } from "next/navigation";
import { API_VERSION } from "@/lib/axios";
import { env } from "@/lib/env";
import { getServerUser } from "@/lib/next-auth/session";
import { Quote } from "@/types/quotes";
// eslint-disable-next-line consistent-return
export const getQuoteDetail = async (quoteId: string): Promise<Quote> => {
try {
const user = await getServerUser();
const response = await fetch(
`${env.NEXT_PUBLIC_API_BASE_URL}/${API_VERSION}/quotes/${quoteId}`,
{
cache: "no-cache",
headers: {
Accesstoken: user.accessToken,
},
}
);
if (!response.ok && response.status === 404) {
throw new Error("Quote not found!");
}
return await response.json();
} catch (error) {
redirect(`/quotes/${quoteId}/not-found`);
}
};
To read more on the server action follow: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations (opens in a new tab)
Steps to Add a Page Title (Deprecated use server component above)
This app uses server side rendering (SSR) to render the pages. To add page title to a page, we need to add meta tags to the page's head section. The head section is rendered on the server side and the meta tags are added to the page's HTML. This allows search engines to crawl the page and index it.
Here's an example of how to add a page title to a page:
import { Metadata } from "next";
export const metadata: Metadata = {
title: "Page Title",
};
export default function Page() {
return <div>Page Content</div>;
}
Refer to the Next.js documentation (opens in a new tab) for more information on how to add meta tags to a page.
Changing page title from a dynamic page
To change the page title from a dynamic page, you can use the useEffect
hook to update the page title when the component mounts. Here's an example:
import { useEffect } from "react";
export default function Page() {
useEffect(() => {
document.title = "Page Title";
}, []);
return <div>Page Content</div>;
}
This will update the page title to "Page Title" when the component mounts. To make it dynamic, you can use a state variable to update the page title based on the state. Example:
import { useEffect, useState } from "react";
export default function Page() {
const [title, setTitle] = useState("Page Title");
useEffect(() => {
document.title = title;
}, [title]);
return (
<div>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<div>Page Content</div>
</div>
);
}