Web Development
How to Add SEO in Next.js: A Production-Ready Guide
Improve your site's visibility with a structured approach to Next.js SEO, from metadata management to dynamic content generation.
By Tushar Gautam · · 6 min read
Short answer
To add SEO in Next.js, use the App Router's Metadata API to define title, description, and Open Graph tags. Generate dynamic OG images using next/og and include JSON-LD schemas for rich snippets. Finally, ensure clean URL structures and use sitemaps to help search engines index your pages effectively.
Key takeaways
- Use the Metadata API in layouts and pages to handle static and dynamic head tags.
- Define a metadataBase in your root layout to allow relative paths for all URL-based metadata fields.
- Generate dynamic Open Graph images using the next/og library for personalized social previews.
- Implement structured data via JSON-LD to qualify for rich snippets in search results.
- Address soft 404 errors by using the notFound() function to return accurate 404 status codes.
Using the Next.js Metadata API for Core SEO
The Metadata API is the foundation of SEO in the Next.js App Router. Instead of manually injecting tags into a document head, you export a static metadata object or an asynchronous generateMetadata function from your layout or page files. This declarative approach allows Next.js to determine the necessary head tags during the build process or at request time, ensuring that search crawlers receive the correct information.
Next.js handles merging these tags from the root layout down to individual pages. This hierarchical merging ensures your title tags, descriptions, and canonical links are always consistent. When you define a title in the root layout, you can use the template property to automatically append page-specific titles, creating a structured and professional presentation in search engine result pages (SERPs).
By utilizing the generateMetadata function, you gain the ability to fetch data from your CMS or database before rendering the page metadata. This is essential for dynamic routes where each page requires a unique title and meta description based on the specific content being displayed. Properly managed metadata prevents configuration drift across a complex application and provides a centralized location to manage SEO settings.
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'My SEO Optimized Page',
description: 'A detailed description for search engines.',
alternates: {
canonical: 'https://tushargautam.software/blog/how-to-add-seo-nextjs',
},
};How to Generate Dynamic Open Graph Images
Open Graph images are crucial for high click-through rates on social platforms. Using next/og, you can generate these images on-the-fly using React components, making them dynamic based on your page content. This avoids the manual effort of creating individual image files for every blog post or article on your platform.
By setting a metadataBase in your root layout, you can easily reference your generated image routes without hardcoding absolute URLs across every single page segment. This ensures that your social media previews always point to the correct, absolute URL, even when your site is deployed across different environments or staging domains.
To implement this, define an image generation function in a dedicated route handler or API route. You can style these components using standard CSS properties supported by the library, allowing you to include branding, post titles, and author names directly on the generated visual. This level of customization ensures that shared links stand out effectively in feeds.
import { ImageResponse } from 'next/og';
export async function GET({ params }) {
return new ImageResponse(
(<div style={{ fontSize: 40, background: 'white', width: '100%', height: '100%' }}>Title</div>),
{ width: 1200, height: 630 }
);
}Implementing JSON-LD for Rich Snippets
Structured data helps Google understand your content as entities, such as Articles, Products, or Organizations. The best way to implement this is by injecting JSON-LD in a script tag within your page components. By providing this semantic machine-readable data, you increase the likelihood of your content appearing as a rich snippet in search results, which can offer more context than a simple link description.
You should treat structured data as a dynamic part of your page. If your page represents a specific blog post, generate the JSON-LD object using the post data to ensure search engines receive the most relevant schema. This object should include key fields like headline, author, datePublished, and dateModified, aligning with industry standards for web content.
Using dangerouslySetInnerHTML is the standard procedure here, as you are injecting a raw JSON string. Ensure that the object is properly sanitized if it contains user-generated input. The schema should be validated against official documentation to ensure that your site structure adheres to the requirements for specific content types like breadcrumbs, how-to guides, or event listings.
export default async function Page({ params }) {
const data = await getBlogData(params.slug);
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'Article',
headline: data.title,
author: 'Tushar Gautam',
};
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
);
}Structuring Sitemaps and Robots.txt
A sitemap acts as a roadmap for search crawlers, ensuring they discover all your important routes. Next.js supports a dynamic sitemap generator that creates an XML file at build time or request time. For smaller sites, a static sitemap file is sufficient, but as your content grows, a dynamic approach ensures that new pages are automatically included in your crawlable index.
Combine this with a simple robots.txt file to instruct crawlers on which areas of your site to index or avoid. This is particularly important for large applications where you want to focus crawler resources on content-heavy pages rather than utility pages, login screens, or temporary development routes. A well-configured robots.txt prevents the crawling of sensitive internal paths.
Managing your sitemap effectively also involves providing metadata like lastModified dates. Providing this information assists crawlers in identifying recently updated content, which can improve the frequency at which your site is re-indexed. Ensure your sitemap is referenced in your robots.txt file so search engines know exactly where to find your updated site map at all times.
Fixing SEO Gotchas: Soft 404s and Canonicalization
A common mistake in Next.js is returning a 200 status code for pages that should be 404. Using the notFound() function in your page logic is the correct way to trigger a 404 response. A soft 404 can confuse search engine crawlers, leading them to index pages that do not actually contain content, which degrades your overall site health and SEO quality.
Always define your canonical URL explicitly in the metadata object. This prevents duplicate content issues, especially when your site is accessible via both www and non-www domains or query parameters. The canonical tag tells search engines which version of a page is the 'master' version, consolidating ranking signals and preventing your pages from competing with each other in search rankings.
When dealing with query parameters or tracking codes that append values to your URLs, canonicalization is even more critical. Using the alternates.canonical field ensures that even if a bot accesses a variant of your URL, it will recognize that the canonical page is the clean, base version. This preserves your SEO authority across different ways users might access your site.
| Feature | SEO Benefit | Next.js Implementation |
|---|---|---|
| Metadata | Better SERP display | metadata object / generateMetadata |
| Canonical | Avoids duplicates | metadata.alternates.canonical |
| JSON-LD | Rich snippets | application/ld+json script tag |
| Sitemap | Better discovery | sitemap.ts file |
When should you avoid aggressive SEO automation?
Over-engineering SEO can occasionally backfire. If your site has highly dynamic user-generated content, ensure that your metadata is not generating excessive load on your database or backend. Constant re-generation of metadata on every request can lead to slow response times, which ultimately hurts user experience and SEO scores.
Automated SEO should never replace content quality. Search engines prioritize helpful, reliable information. Focus your efforts on clear headings, relevant keywords, and high-quality internal linking before obsessing over meta tags. An automated tool cannot compensate for thin, unhelpful, or poorly structured content.
Monitor your performance metrics closely to ensure that your metadata generation processes are not causing latency. If you observe performance drops, consider implementing caching strategies or generating certain metadata statically at build time. Balancing automated efficiency with human-driven quality is the key to a sustainable long-term SEO strategy for any Next.js application.
Frequently asked questions
Should I use static metadata or generateMetadata?
Use static metadata for pages where the content does not change, such as the homepage or contact page. Use generateMetadata for dynamic routes where SEO data depends on external database queries or route parameters.
How do I prevent search engines from indexing specific pages?
You can prevent indexing by adding robots: { index: false } to your metadata object. This will inject the appropriate noindex tag, telling crawlers to ignore the page.
Is JSON-LD still relevant for SEO?
Yes, JSON-LD is the preferred format for Google to understand structured data. It helps your site qualify for rich snippets, which can significantly increase click-through rates compared to standard search results.
Sources & further reading
Work with me
Building something like this?
I build AI-powered products with Next.js, Python and LLM APIs, from first prototype to production. If you need help with a project, a second opinion on your architecture, or a developer on your team, get in touch.
About the author
Tushar Gautam is a full-stack & ai product engineer in India. He builds AI SaaS products such as an AI video ad generator, a RAG chatbot platform and a Razorpay-powered report service, mostly with Next.js, Flask and the Gemini API. See the projects, GitHub or LinkedIn.
This article was drafted with the help of AI (Google Gemini) from official documentation and published by Tushar Gautam. Spotted an error? Let me know.