Next.js Metadata & SEO
Good Next.js SEO starts with giving search engines and social networks the right information about every page. The App Router includes a built-in Metadata API that generates the correct <head> tags for you, without any extra packages. When you combine that with Server Components, the HTML that reaches a crawler already contains your content and metadata.
This tutorial shows you how to export a static metadata object from a layout, use generateMetadata for dynamic pages, and set up a title template so every page has a consistent suffix. You will also create app/sitemap.ts and app/robots.ts, add JSON-LD structured data safely, and walk through a checklist of on-page SEO basics that every Next.js project should follow.
If you have not worked with dynamic routes yet, read Next.js Dynamic Routes first, because generateMetadata receives the same params object. For image-related SEO, including alt text and Open Graph images, see Next.js Image Optimization.
What Is the Next.js Metadata API?
The Next.js Metadata API is a set of conventions for defining page metadata inside Server Components. You either export a static metadata object or an async generateMetadata function, and Next.js turns the result into the appropriate <head> tags . It replaces the need for a separate next/head component and works only in Server Components.
// app/about/page.tsx
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "About Us",
description: "Learn about our team and mission.",
};
export default function AboutPage() {
return <h1>About Us</h1>;
}
Browser shows: The page tab reads About Us, and the page source contains <meta name="description" content="Learn about our team and mission." />. You did not write any <head> tags yourself.
How it works: Next.js reads the exported metadata object at build time (or request time for dynamic pages) and injects the matching tags into the HTML. The object supports many fields: title, description, openGraph, twitter, alternates, robots, and more . Because the export only works in Server Components, the metadata is resolved on the server before the page is sent, which is exactly what crawlers need.
Static Metadata, Title Templates, and Inheritance
Static metadata is an object you export when the values do not depend on request data. A common pattern is to define a title template in the root layout so every child page inherits a consistent suffix .
// app/layout.tsx
import type { Metadata } from "next";
export const metadata: Metadata = {
title: {
default: "Online Learner",
template: "%s | Online Learner",
},
description: "Free programming tutorials for beginners.",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
// app/blog/page.tsx
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "Blog",
};
export default function BlogPage() {
return <h1>Blog</h1>;
}
Browser shows: The blog page tab reads Blog | Online Learner. A page that does not set a title falls back to the default value, Online Learner.
How it works: Metadata flows from the root layout down to child segments. A page's title string is inserted into the parent's template using the %s placeholder. If a page sets no title, the parent's default is used. This inheritance works for other fields too, but title is the most visible benefit. You cannot export both metadata and generateMetadata from the same segment .
Dynamic Metadata with generateMetadata and Awaited Params
generateMetadata is an async function you export from a dynamic page. It receives the same params and searchParams as the page component, and in Next.js 16 both are Promises that must be awaited .
// app/blog/[slug]/page.tsx
import type { Metadata } from "next";
type Post = {
title: string;
description: string;
};
type Props = {
params: Promise<{ slug: string }>;
};
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${slug}`);
const post: Post = await response.json();
return {
title: post.title,
description: post.description,
alternates: {
canonical: `https://onlinelearner.in/blog/${slug}`,
},
};
}
export default async function BlogPostPage({ params }: Props) {
const { slug } = await params;
return <h1>Post {slug}</h1>;
}
Browser shows: The tab title matches the post title from the API, the description matches the post body excerpt, and the page source contains a <link rel="canonical" href="https://onlinelearner.in/blog/1" /> tag.
How it works: Next.js calls generateMetadata as part of rendering the page. If the page is prerendered, the metadata is baked into the initial HTML. If the page is dynamic, the metadata may stream in after the UI, but bots that expect metadata in the <head> receive it in the initial response . The alternates.canonical field tells search engines which URL is the preferred version, which prevents duplicate-content issues when the same post is reachable through multiple URLs.
Sitemap and Robots Files
Next.js can generate sitemap.xml and robots.txt from TypeScript files in the app directory. This keeps both files in sync with your routes and database .
app/sitemap.ts
// app/sitemap.ts
import type { MetadataRoute } from "next";
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const baseUrl = "https://onlinelearner.in";
const posts = [
{ slug: "next-js-data-fetching", updatedAt: new Date("2026-01-10") },
{ slug: "next-js-route-handlers-api", updatedAt: new Date("2026-01-12") },
];
return [
{
url: baseUrl,
lastModified: new Date(),
changeFrequency: "weekly",
priority: 1,
},
...posts.map((post) => ({
url: `${baseUrl}/nextjs-tutorial/${post.slug}`,
lastModified: post.updatedAt,
changeFrequency: "monthly" as const,
priority: 0.7,
})),
];
}
Output: Visiting /sitemap.xml returns a valid XML sitemap listing the home page and each tutorial URL, with lastModified dates and changeFrequency hints.
app/robots.ts
// app/robots.ts
import type { MetadataRoute } from "next";
export default function robots(): MetadataRoute.Robots {
return {
rules: [
{
userAgent: "*",
allow: "/",
disallow: ["/api/", "/admin/"],
},
],
sitemap: "https://onlinelearner.in/sitemap.xml",
host: "https://onlinelearner.in",
};
}
Output: Visiting /robots.txt returns rules that allow all crawlers to index the public site, block /api/ and /admin/, and point to the sitemap URL.
How it works: The sitemap.ts file exports a function that returns an array of route objects. Next.js serves the result at /sitemap.xml. The robots.ts file exports a function that returns a rules object, served at /robots.txt. The sitemap field in the robots object tells crawlers where to find your sitemap. Both files can be async if they need to fetch data .
Open Graph Images and JSON-LD Structured Data
Open Graph images control how your links look when shared on social media. You can place an opengraph-image.png file in any route segment, and Next.js adds the appropriate og:image tags automatically .
app/
blog/
opengraph-image.png
opengraph-image.alt.txt
page.tsx
Output: Sharing a link to /blog on social media shows the image with the alt text from the .txt file. The generated tags include og:image, og:image:width, og:image:height, and og:image:alt.
JSON-LD structured data helps search engines understand the content type. Add it as a <script> tag in a Server Component, and escape < characters in the JSON to prevent injection .
// app/blog/[slug]/page.tsx
export default async function BlogPostPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const jsonLd = {
"@context": "https://schema.org",
"@type": "BlogPosting",
headline: "Next.js Data Fetching",
author: { "@type": "Person", name: "Online Learner" },
};
return (
<article>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(jsonLd).replace(/</g, "\\u003c"),
}}
/>
<h1>Post {slug}</h1>
</article>
);
}
Output: The page source contains a valid JSON-LD block. Google's Rich Results Test can validate it without errors.
How it works: The dangerouslySetInnerHTML prop is the recommended way to render JSON-LD because the data is not executable JavaScript. The .replace(/</g, "\\u003c") step escapes any < characters, so a string containing </script> cannot close the script tag early. Do not use next/script for JSON-LD; a native script tag is the correct choice .
Why Server Components Help Next.js SEO
Server Components render on the server and send complete HTML to the browser. When a crawler requests your page, it receives the content immediately, without waiting for JavaScript to download and run. This makes your pages easier to index and improves the accuracy of how search engines understand your content .
The Metadata API also only works in Server Components, which means your titles and descriptions are resolved on the server and included in the initial response. For dynamic pages, Next.js is careful to send metadata in the <head> for crawlers that need it, even when it streams the UI for regular users.
On-Page SEO Checklist
This table summarizes the basics every Next.js page should have. Use it as a quick audit before launching a project.
| Check | What to do | Where |
|---|---|---|
| Unique title | Every page needs a distinct title; use a template for the suffix |
metadata or generateMetadata |
| Unique description | Write a specific description for each page, not a copy of the title |
metadata or generateMetadata |
| Headings | One <h1> per page, use <h2> and <h3> for structure |
Page component |
| Canonical URL | Set alternates.canonical on dynamic pages to avoid duplicates |
generateMetadata |
| Sitemap | List all public pages with lastModified dates |
app/sitemap.ts |
| Robots | Allow public pages and block private paths | app/robots.ts |
Common Mistakes and Best Practices
- Forgetting to await
paramsingenerateMetadata. In Next.js 16,paramsis a Promise. Accessingparams.slugdirectly gives you a warning andundefined, so your title becomes undefined | Site Name . - Exporting both
metadataandgenerateMetadatafrom the same file. Next.js does not know which one to use and reports a build error. Pick one. Usemetadatafor static values andgenerateMetadatafor dynamic ones . - Reusing the same description on every page. Search engines may ignore duplicate descriptions or pick their own text. Write a specific description for each page, even if it is short.
- Forgetting to escape
<in JSON-LD. A string containing</script>can break the page or create an XSS vulnerability. Always replace<with\\u003cafterJSON.stringify. - Blocking CSS or JS in
robots.txt. Search engines need these files to render your page correctly. Blocking/_next/can prevent Google from seeing your styled content. Only block paths that contain private data, like/api/and/admin/. - Setting
openGraph.imagesand also placing anopengraph-imagefile. The explicitopenGraph.imagesvalue overrides the file. Pick one approach per route to avoid confusion .
Real-World Example: A Tutorial Page with Full Metadata
This example combines a root layout with a title template, a dynamic tutorial page with generateMetadata and JSON-LD, a sitemap, and a robots file.
// app/layout.tsx
import type { Metadata } from "next";
export const metadata: Metadata = {
title: {
default: "Online Learner",
template: "%s | Online Learner",
},
description: "Free programming tutorials for beginners.",
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
// app/nextjs-tutorial/[slug]/page.tsx
import type { Metadata } from "next";
type Tutorial = {
title: string;
description: string;
};
type Props = {
params: Promise<{ slug: string }>;
};
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const tutorials: Record<string, Tutorial> = {
"next-js-data-fetching": {
title: "Next.js Data Fetching",
description: "Learn how to fetch data in async Server Components.",
},
};
const tutorial = tutorials[slug] ?? {
title: "Tutorial Not Found",
description: "This tutorial does not exist.",
};
return {
title: tutorial.title,
description: tutorial.description,
alternates: {
canonical: `https://onlinelearner.in/nextjs-tutorial/${slug}`,
},
};
}
export default async function TutorialPage({ params }: Props) {
const { slug } = await params;
const jsonLd = {
"@context": "https://schema.org",
"@type": "TechArticle",
headline: "Next.js Data Fetching",
};
return (
<article>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(jsonLd).replace(/</g, "\\u003c"),
}}
/>
<h1>{slug}</h1>
</article>
);
}
Line-by-line explanation:
- The root layout sets a
title.templatewith%s | Online Learner. Any child page that exports a string title gets this suffix automatically. - The dynamic page exports
generateMetadata, which awaitsparamsand returns aMetadataobject withtitle,description, andalternates.canonical. - The canonical URL tells search engines that
https://onlinelearner.in/nextjs-tutorial/next-js-data-fetchingis the preferred version of the page. - The page component renders a JSON-LD script with
dangerouslySetInnerHTMLand the.replace(/</g, "\\u003c")safety step. - In a real project, the sitemap and robots files from earlier sections complete the setup.
Summary
- Next.js SEO starts with the Metadata API: export a
metadataobject for static pages orgenerateMetadatafor dynamic pages. - Use a
title.templatein the root layout to give every page a consistent suffix, and setalternates.canonicalon dynamic routes. - Create
app/sitemap.tsandapp/robots.tsto tell search engines what to crawl and where to find your pages. - Add JSON-LD with a native
<script>tag and escape<characters to prevent injection. - Server Components deliver complete HTML to crawlers, which makes your content easier to index.
- Follow the on-page checklist: unique titles, unique descriptions, proper headings, canonical URLs, a sitemap, and a robots file.
Now that your pages are search-friendly, the next step is styling them efficiently. Continue with Tailwind CSS with Next.js.
Frequently Asked Questions
Can I use generateMetadata in a Client Component?
No. The metadata object and generateMetadata function are only supported in Server Components. If you have a Client Component page, create a sibling layout.tsx that is a Server Component and export the metadata there. This keeps the metadata on the server while your interactive page remains a Client Component.
What happens if I don't set a title for a page?
The page inherits the nearest parent's title. If the root layout has a title.default, that value is used. If no parent sets a title, Next.js falls back to the route segment name or a generic value. It is best to set a meaningful title on every page, even if it relies on a template for the suffix.
How do I prevent a page from appearing in search results?
Export a metadata object with robots: { index: false, follow: false }. This adds a noindex, nofollow meta tag to the page. You can also disallow the path in robots.ts, but the meta tag is more reliable because it applies even if the page is linked from elsewhere.
Do I need both sitemap.ts and robots.ts?
They serve different purposes. sitemap.ts lists your public URLs so search engines can discover them. robots.ts tells crawlers which paths they may or may not visit, and points to the sitemap. You can have a sitemap without a robots file, but adding both gives you full control over crawling.
Why is my JSON-LD not showing up in Google's Rich Results Test?
Check three things: the script type must be application/ld+json, the JSON must be valid after the .replace(/</g, "\\u003c") step, and the script must be inside the page's rendered HTML. Use your browser's "View Page Source" to confirm the script is present. If you used next/script instead of a native script tag, it may not render correctly for structured data.
Practice Exercises
Easy: Add a static title and description
Create a page at app/contact/page.tsx with a static metadata export that sets the title to Contact Us and the description to Get in touch with our team.
Show solution
// app/contact/page.tsx
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "Contact Us",
description: "Get in touch with our team.",
};
export default function ContactPage() {
return <h1>Contact Us</h1>;
}
The metadata object is exported from a Server Component and Next.js generates the <head> tags automatically.
Easy: Set up a title template
Update the root layout to use a title template where child page titles appear as [Page Title] | My Site.
Show solution
// app/layout.tsx
import type { Metadata } from "next";
export const metadata: Metadata = {
title: {
default: "My Site",
template: "%s | My Site",
},
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
Child pages that export a string title get the template applied automatically.
Medium: Add generateMetadata to a dynamic route
Create a dynamic page at app/products/[id]/page.tsx. Use generateMetadata to await params and return a title that includes the product ID.
Show solution
// app/products/[id]/page.tsx
import type { Metadata } from "next";
type Props = {
params: Promise<{ id: string }>;
};
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { id } = await params;
return {
title: `Product ${id}`,
description: `Details for product ${id}.`,
};
}
export default async function ProductPage({ params }: Props) {
const { id } = await params;
return <h1>Product {id}</h1>;
}
The params Promise is awaited before reading id, which is required in Next.js 16.
Challenge: Create sitemap.ts and robots.ts
Add a sitemap.ts that lists the home page and a /about page, and a robots.ts that allows all crawlers and points to the sitemap.
Show solution
// app/sitemap.ts
import type { MetadataRoute } from "next";
export default function sitemap(): MetadataRoute.Sitemap {
const baseUrl = "https://example.com";
return [
{ url: baseUrl, lastModified: new Date(), priority: 1 },
{ url: `${baseUrl}/about`, lastModified: new Date(), priority: 0.8 },
];
}
// app/robots.ts
import type { MetadataRoute } from "next";
export default function robots(): MetadataRoute.Robots {
return {
rules: [{ userAgent: "*", allow: "/" }],
sitemap: "https://example.com/sitemap.xml",
};
}
Next.js serves sitemap.ts at /sitemap.xml and robots.ts at /robots.txt automatically.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
