Next.jsMedium

How do you implement SEO in Next.js?

Render content on the server (Server Components, prerendered static shells), define titles, descriptions, canonical URLs and Open Graph data with the Metadata API, generate sitemap.xml and robots.txt from code, add structured data (JSON-LD), use semantic HTML, and keep Core Web Vitals healthy with next/image, next/font and minimal client JavaScript.

Checklist

  1. Server-rendered HTML: content in Server Components is in the initial HTML, so crawlers see it without running JavaScript.
  2. Metadata API: export const metadata or generateMetadata in layouts and pages, with a title.template in the root layout.
  3. Canonical and alternates: alternates: { canonical, languages } for duplicates and hreflang.
  4. Social cards: openGraph, twitter, and generated images with opengraph-image.tsx.
  5. Sitemap and robots: app/sitemap.ts and app/robots.ts; generateSitemaps for large sites.
  6. Structured data: a <script type="application/ld+json"> in the page (escape < characters).
  7. Status codes: notFound() for 404s, permanentRedirect() for moved content, no soft 404s.
  8. Clean URLs: descriptive slugs, trailingSlash consistency, no duplicate paths.
  9. Performance: LCP, INP and CLS are ranking signals.
  10. Accessibility and semantics: headings in order, alt text, lang on <html>.

Streaming metadata

Since 15.2, generateMetadata can stream after the shell for normal browsers. Next.js detects bots that need metadata in <head> (configurable with htmlLimitedBots) and renders it before streaming.

Pages Router

next/head for tags, and getStaticProps for prerendered content.

Code example

tsx
1// app/blog/[slug]/page.tsx
2import type { Metadata } from "next";
3import { notFound } from "next/navigation";
4import { getPost } from "@/lib/posts";
5
6export async function generateMetadata({ params }: PageProps<"/blog/[slug]">): Promise<Metadata> {
7 const { slug } = await params;
8 const post = await getPost(slug);
9 if (!post) return {};
10 return {
11 title: post.title,
12 description: post.excerpt,
13 alternates: { canonical: `/blog/${slug}` },
14 openGraph: { type: "article", publishedTime: post.publishedAt, authors: [post.author] },
15 };
16}
17
18export default async function Post({ params }: PageProps<"/blog/[slug]">) {
19 const { slug } = await params;
20 const post = await getPost(slug);
21 if (!post) notFound();
22
23 const jsonLd = { "@context": "https://schema.org", "@type": "BlogPosting", headline: post.title, datePublished: post.publishedAt };
24 return (
25 <article>
26 <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }} />
27 <h1>{post.title}</h1>
28 </article>
29 );
30}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app