Skip to content
Vibe Code Basics
Next.js

Next.js SEO Guide: Metadata API, Sitemaps, Robots.txt & Open Graph Images

A complete Next.js 16 SEO setup: metadataBase, title templates, canonical URLs, Open Graph and Twitter cards, generated OG images, sitemap.xml, robots.txt and JSON-LD structured data, with copy-paste code.

By Vibe Code Basics Editorial TeamPublished Updated 3 min read
On this page (13)

Next.js has SEO built in through the Metadata API and special metadata files. Export a metadata object (or a generateMetadata function) from any page or layout to set titles, descriptions, canonical URLs and social tags, and add sitemap.ts, robots.ts and opengraph-image.tsx files to generate the rest automatically.

This is the exact setup used on Vibe Code Basics. If you're vibe coding a site, you can hand this guide to your AI agent as a checklist. New to Next.js? Read Getting Started with Next.js first.

The SEO checklist

  1. metadataBase and a title template in the root layout
  2. A unique title and description on every page
  3. A canonical URL on every page
  4. Open Graph and Twitter card tags
  5. Social share images (generated automatically)
  6. sitemap.xml with accurate last-modified dates
  7. robots.txt pointing to the sitemap
  8. JSON-LD structured data
  9. Real 404s for missing pages
  10. Fast pages (see image optimization)

1. Root layout: metadataBase and title template

// app/layout.tsx
import type { Metadata } from 'next';

export const metadata: Metadata = {
  metadataBase: new URL('https://example.com'),
  title: {
    default: 'Example: Build Apps with AI',
    template: '%s | Example',
  },
  description: 'Practical guides to building software with AI coding agents.',
  openGraph: {
    type: 'website',
    siteName: 'Example',
    locale: 'en_US',
  },
  twitter: { card: 'summary_large_image' },
  robots: { index: true, follow: true },
};

metadataBase lets you use relative URLs everywhere else; Next.js turns them into absolute URLs, which Open Graph requires. The title template means a page that sets title: 'Pricing' renders as "Pricing | Example".

2. Page metadata and canonical URLs

// app/pricing/page.tsx
export const metadata = {
  title: 'Pricing',
  description: 'Simple, transparent pricing. Start free, upgrade when you grow.',
  alternates: { canonical: '/pricing' },
};

A canonical URL tells search engines which URL is the "real" one, protecting you from duplicate-content issues caused by query strings, trailing slashes or www vs non-www.

Write descriptions for humans: around 140–160 characters that summarize the page and give a reason to click. The keywords meta tag is ignored by Google, so don't bother with it.

3. Dynamic metadata with generateMetadata

// app/blog/[slug]/page.tsx
export async function generateMetadata({ params }: PageProps<'/blog/[slug]'>) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) return {};

  return {
    title: post.title,
    description: post.description,
    alternates: { canonical: `/blog/${slug}` },
    openGraph: {
      type: 'article',
      title: post.title,
      description: post.description,
      url: `/blog/${slug}`,
      publishedTime: post.date,
      modifiedTime: post.updated,
    },
  };
}

Remember params is a Promise in Next.js 16. Next.js deduplicates data requests, so fetching the post in both generateMetadata and the page is fine.

4. Generated Open Graph images

Instead of designing a share image for every page, generate them. Add opengraph-image.tsx to any route segment:

// app/blog/[slug]/opengraph-image.tsx
import { ImageResponse } from 'next/og';

export const size = { width: 1200, height: 630 };
export const contentType = 'image/png';

export default async function Image({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await getPost(slug);

  return new ImageResponse(
    (
      <div
        style={{
          width: '100%',
          height: '100%',
          display: 'flex',
          alignItems: 'flex-end',
          padding: 80,
          background: '#101116',
          color: 'white',
          fontSize: 72,
          fontWeight: 700,
        }}
      >
        {post.title}
      </div>
    ),
    size
  );
}

Next.js automatically adds the og:image and twitter:image tags, and the image is generated at build time for static pages. Every article on this site uses this technique.

5. sitemap.xml

// app/sitemap.ts
import type { MetadataRoute } from 'next';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = await getAllPosts();

  return [
    { url: 'https://example.com', lastModified: new Date(posts[0].updated) },
    { url: 'https://example.com/blog', lastModified: new Date(posts[0].updated) },
    ...posts.map((post) => ({
      url: `https://example.com/blog/${post.slug}`,
      lastModified: new Date(post.updated),
    })),
  ];
}

Two tips:

  • Use real modification dates. Setting lastModified: new Date() on every URL tells Google everything changed on every build, which teaches it to ignore your dates.
  • Skip priority and changeFrequency. Google ignores them (opens in a new tab).

Submit https://yoursite.com/sitemap.xml in Google Search Console (opens in a new tab) and Bing Webmaster Tools.

6. robots.txt

// app/robots.ts
import type { MetadataRoute } from 'next';

export default function robots(): MetadataRoute.Robots {
  return {
    rules: [{ userAgent: '*', allow: '/', disallow: ['/api/', '/admin/'] }],
    sitemap: 'https://example.com/sitemap.xml',
  };
}

robots.txt controls crawling, not indexing. To keep a page out of search results, use robots: { index: false } in its metadata instead. And think carefully before blocking AI crawlers: for many content sites, being cited in AI answers is valuable traffic.

7. Structured data (JSON-LD)

Structured data helps search engines understand your content and can unlock rich results:

export default async function BlogPost({ params }: PageProps<'/blog/[slug]'>) {
  const { slug } = await params;
  const post = await getPost(slug);

  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'BlogPosting',
    headline: post.title,
    description: post.description,
    datePublished: post.date,
    dateModified: post.updated,
    author: { '@type': 'Organization', name: 'Example' },
  };

  return (
    <article>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c') }}
      />
      <h1>{post.title}</h1>
    </article>
  );
}

The .replace(/</g, '\\u003c') prevents content containing </script> from breaking out of the tag, a subtle XSS risk that AI-generated examples usually miss. Validate with Google's Rich Results Test (opens in a new tab). Useful types include BlogPosting, BreadcrumbList, Organization, WebSite and Product.

8. Return real 404s

import { notFound } from 'next/navigation';

const post = await getPost(slug);
if (!post) notFound();

Rendering "Post not found" with a 200 status creates "soft 404s" that waste crawl budget.

Testing your SEO

  • View source and check the <head> for titles, canonicals and OG tags.
  • Google Rich Results Test for structured data.
  • Lighthouse in Chrome DevTools for SEO and performance scores.
  • Social preview tools like the LinkedIn Post Inspector and Facebook Sharing Debugger.
  • Google Search Console to monitor indexing and search performance over time.

Content still matters most

Technical SEO gets your pages crawled and displayed well. What ranks them is genuinely useful, up-to-date content with a clear structure, internal links between related pages, and links to authoritative sources. That's why we refresh every guide on this site as tools change.

Prompt for your AI agent

Audit this Next.js 16 app's SEO against this checklist: metadataBase and title template,
unique title/description and canonical on every page, generated opengraph-image for
blog posts, sitemap.ts with real lastModified dates, robots.ts with sitemap, BlogPosting
and BreadcrumbList JSON-LD (escape "<"), notFound() for missing content.
List gaps first, then fix them one at a time.

See more in our prompting guide and the official Metadata docs (opens in a new tab).

Next steps

  • #Next.js
  • #SEO
  • #Metadata
  • #Tutorial

Keep reading