Web Development
How to Improve SEO in Next.js: A Production-Ready Guide
Boost your Next.js search rankings with a production-tested strategy covering the Metadata API, structured data, and dynamic image generation.
By Tushar Gautam · · 7 min read
Short answer
Improving SEO in Next.js requires a layered approach: use the Metadata API for static and dynamic tags, implement structured JSON-LD for rich results, generate dynamic Open Graph images with @vercel/og, and ensure your sitemaps are accurate. Proper handling of canonical URLs and avoiding soft 404 errors are critical for successful indexation.
Key takeaways
- Use the Metadata API for both static and dynamic page configurations to avoid layout shifts and ensure accurate indexing.
- Implement dynamic Open Graph images using @vercel/og to make your content shareable and clickable on social platforms.
- Inject JSON-LD structured data via server components to communicate content context to search engine crawlers.
- Fix soft 404s by explicitly using the notFound() function in the App Router to ensure Google ignores non-existent pages.
How to use the Metadata API for dynamic pages?
The App Router replaces the previous Head component with the Metadata API. This system allows you to define tags in a more declarative way, ensuring that metadata is generated before the page reaches the client. For dynamic pages, you must export a generateMetadata function. This function permits you to fetch data once and share it between the layout and the page component.
When defining generateMetadata, the function receives the route parameters and search parameters. You can use these values to query your database or external API. The function should return an object that aligns with the Metadata type, ensuring that fields like title, description, and openGraph are populated correctly based on your content.
Ensure your dynamic metadata returns an object containing title, description, and openGraph properties. This ensures every route provides unique signals to search engines instead of defaulting to your root layout settings. By separating the metadata logic, you keep your page components focused purely on rendering UI while the metadata logic resides in a dedicated, server-side execution path.
Furthermore, the Metadata API supports field merging. If you define global metadata in your root layout, the child pages can override specific fields while inheriting the rest. This is particularly useful for sitewide branding tags that remain constant, such as Open Graph site names, while allowing page-specific content to remain unique.
export async function generateMetadata({ params }) {
const post = await getPost(params.slug);
return {
title: post.title,
description: post.excerpt,
openGraph: {
images: [`/api/og?title=${post.title}`],
},
};
}Why is JSON-LD critical for your ranking?
Structured data (JSON-LD) acts as a bridge between your raw content and the crawlers that index it. By formatting data into a standardized structure, you help machines interpret the context of your page, whether it is a blog post, a product description, or author information. Providing this context increases the probability of appearing in search engine rich snippets.
Implementing JSON-LD in the App Router is straightforward because you can treat the structured data as a simple JavaScript object. By rendering this object into a script tag with the application/ld+json type, you deliver the metadata directly in the initial HTML payload. This is superior to client-side injection, which might be missed by crawlers if they do not execute JavaScript fully.
Always keep your schema valid. Use the Schema Markup Validator to verify that your JSON output aligns with Google's expected formats for Article or WebSite entities. Testing your markup early prevents errors where search engines might reject your structured data due to missing required fields like 'publisher' or 'dateModified'.
When managing complex pages, such as e-commerce product pages, you can include multiple types of JSON-LD, such as Product and BreadcrumbList, on the same page. Simply define them as separate objects or an array of objects within the same script tag. This ensures crawlers receive a comprehensive view of the entity's attributes and relationships.
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'Article',
headline: post.title,
datePublished: post.date,
};
export default function Page() {
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
);
}How to handle dynamic Open Graph images?
Static images are often insufficient for sites with large amounts of dynamic content. Manually creating an OG image for every single blog post is time-consuming and prone to human error. By using the @vercel/og library, you can generate social media preview images on the fly during the request, pulling titles or categories directly from your database.
These images improve CTR (Click-Through Rate) significantly, as they provide visual context before the user even clicks the link. When the request hits your API route, the @vercel/og library constructs an image using HTML and CSS, which is then rendered as an optimized PNG. This process is fast enough to run in real-time.
Place these API routes in /app/api/og/route.tsx to keep your project structure clean and manageable. Within the handler, you can extract query parameters from the URL to customize the image text, background color, and layout based on the specific content being requested. This flexibility allows your branding to remain consistent across all shared links.
Cache management is also a benefit here. Because the image is served from a standard URL, the CDN will cache the generated result after the first request. This means subsequent users receive the image near-instantly without hitting your database or recalculating the image generation logic repeatedly.
How to stop soft 404 errors in Next.js?
A soft 404 happens when your server returns a 200 OK status for a page that does not exist. This happens if you return an empty object or a generic error component instead of signaling to the crawler that the URL is invalid. This behavior wastes your crawl budget and creates noise in your search index.
When a resource is missing, you must call the notFound() function provided by next/navigation. This function stops the current page rendering and instructs the Next.js server to send a 404 status code. This is the correct way to inform search engines that the page should not be indexed, effectively managing your crawl budget and preventing duplicate or empty pages from appearing in search results.
To verify that your error handling works correctly, check the HTTP headers in your browser's network tab when navigating to a non-existent route. You should see a 404 status. If you see a 200, the page is not properly triggering the notFound function. This simple check is essential for maintaining the health of your site within search engine indices.
You can also use this approach for nested routes or dynamic segments. By checking your data sources—such as verifying if a database query returned a null value—you can conditionally trigger the notFound function before the layout is even fully constructed. This prevents the browser from rendering shells of pages that lack content.
import { notFound } from 'next/navigation';
export default async function Page({ params }) {
const data = await fetchData(params.slug);
if (!data) notFound();
return <div>{data.content}</div>;
}SEO implementation: A Comparison
Choosing the right approach depends on your scale. Here is a breakdown of how to handle core SEO tasks in the Next.js App Router.
The table below highlights the divergence between recommended practices and common pitfalls. Following these patterns helps ensure that your application behaves predictably for both users and automated crawlers.
By sticking to the 'Best Practice' column, you minimize the risk of missing critical metadata tags or inadvertently serving malformed content that search engines might ignore during the parsing phase of indexing.
| Task | Best Practice | Common Mistake |
|---|---|---|
| Metadata | generateMetadata() | Using <head> in pages |
| Structured Data | Server-side JSON-LD | Client-side injection |
| 404 Errors | notFound() function | Returning empty objects |
| Sitemaps | sitemap.ts dynamic gen | Hardcoded static sitemap |
What are the common SEO gotchas?
Canonical URLs are the most ignored aspect of SEO. If your site generates content with query parameters or varied URL patterns that lead to the same content, search engines may treat these as duplicates. You must use the alternates.canonical metadata field to point specifically to the base URL that you want to be the source of truth.
Avoid over-fetching data in your layout files. Since metadata is requested for every route in the App Router, heavy database operations in layouts will increase response times. Because metadata is part of the initial render, slow responses here delay the First Contentful Paint, which hurts your Core Web Vitals and ultimately impacts your ranking.
Another aspect to monitor is the use of 'noindex' tags during development. It is easy to add a global noindex tag for testing, but forgetting to remove it before deployment is a common reason for a site to fail to appear in search results. Always perform a final check of your production output to ensure indexable pages are not marked as hidden.
Finally, ensure your sitemap is up to date. Next.js supports dynamic sitemap generation, which is superior to static files that require manual updates. By automating the sitemap, you ensure that every new page created in your database is automatically included in the file and ready for submission to Google Search Console.
Frequently asked questions
Should I use metadata in every layout or just pages?
Use layouts for global metadata like sitewide title templates and favicons. Use individual pages and generateMetadata() for unique content-specific tags.
How do I check if my SEO changes are working?
Use the Google Search Console 'URL Inspection' tool. It allows you to see the rendered HTML as Googlebot sees it, confirming if your metadata and JSON-LD are being injected correctly.
Does Vercel Hobby plan affect SEO performance?
Not directly. While Hobby plans have some infrastructure limitations, Next.js generates static assets and optimized HTML that perform well on any tier as long as your code is efficient.
Sources & further reading
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.