09 / GUIDE · NEXT.JS & MARKDOWNP1 · Code-Level Guide12 min readUpdated November 13, 2026
nextjs seo
For the Next.js 16 App Router, keep primary content in server-rendered or statically rendered output, use route-specific metadata and publish consistent canonical URLs, sitemaps and robots rules. Check the generated response rather than assuming a framework setting guarantees indexing.
The companion application declares Next.js 16.4.3; the marketing site you are reading is static HTML. The patterns below use the Next.js 16 async params API. Audit Open Graph metadata, descriptive internal links, valid JSON-LD and performance alongside indexability. Official reference: Next.js metadata API.
Next.js App Router gives developers first-class metadata APIs, typed sitemaps, and server components—yet small configuration oversights in layout.tsx, generateMetadata, or middleware.ts regularly prevent entire Markdown blogs and product pages from being indexed. Here are the exact code patterns to audit and fix.
QUESTION ASKED (P15)“How do I audit indexing, metadata and canonicals on a Next.js site?”
Direct answer: Audit a Next.js App Router site across five code checkpoints: (1) verify metadataBase is set to your production HTTPS origin in app/layout.tsx and that child routes define their own alternates.canonical instead of inheriting the root / canonical; (2) check that dynamic routes call notFound() for missing slugs rather than returning HTTP 200 with a “Post not found” message (a soft 404); (3) ensure app/sitemap.ts outputs final canonical URLs matching your trailingSlash setting; (4) verify middleware.ts and next.config.ts use permanent 308/301 redirects rather than default 307 temporary redirects; and (5) confirm preview deployments emit X-Robots-Tag: noindex without leaking that header to your production domain.
01 / CANONICAL URL BUGS
The #1 Next.js indexing bug: root alternates.canonical inheritance
In Next.js App Router, developers often set metadataBase: new URL("https://example.com") and alternates: { canonical: "/" } inside the root app/layout.tsx, assuming Next.js will automatically set each child page’s canonical to its own pathname. It does not.
If a child page (`app/blog/[slug]/page.tsx`) defines title and description in generateMetadata without overriding alternates.canonical, Next.js shallow-merges or inherits the parent layout’s alternates object—or omits the canonical altogether depending on your layout tree. When child pages inherit <link rel="canonical" href="https://example.com/">, you are explicitly instructing Google that every blog post on your site is a duplicate of your homepage.
BEFORE vs. AFTER · NEXT.JS CANONICAL CONFIGURATIONapp/blog/[slug]/page.tsx
Preventing soft 404s and client-only rendering traps
When auditing a Markdown or CMS-backed Next.js blog, check two rendering behaviors on every dynamic route:
Always call notFound() from next/navigation when a slug is missing: If a user or bot requests /blog/deleted-article and your component renders <div>Article not found</div> without calling notFound(), Next.js serves that page with HTTP status 200 OK. Google Search Console flags this as a Soft 404 and wastes crawl budget on dead URLs.
Keep primary article prose and headings in Server Components: While Googlebot executes JavaScript, fetching your primary article body or <h1> inside a client-side useEffect() delays content discovery, breaks OpenGraph link previews (which do not run JS), and risks empty renders when API calls time out.
03 / SITEMAP ALIGNMENT
Why a Next.js sitemap says “Submitted, not indexed”
Next.js makes it easy to generate a sitemap via app/sitemap.ts. However, two subtle mismatches frequently cause Search Console to reject or ignore URLs in /sitemap.xml:
Mismatch with trailingSlash in next.config.ts: If you deploy a static export (`output: "export"`) on Cloudflare Pages or S3 with trailingSlash: true, every page resolves at /blog/post-slug/. If your app/sitemap.ts outputs https://example.com/blog/post-slug (without the trailing slash), every single URL in your sitemap triggers a 308 redirect! Your sitemap and your canonical tags must use the exact same trailing-slash convention.
Using new Date() for every entry’s lastModified: Setting lastModified: new Date() on every post in app/sitemap.ts stamps the current build time on articles you haven’t touched in two years. Always pass the post’s actual updatedAt or Git commit date.
CLEAN NEXT.JS SITEMAP GENERATORapp/sitemap.ts
import type { MetadataRoute } from "next";
import { getAllPosts } from "@/lib/posts";
const ORIGIN = "https://yourdomain.com";
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const posts = await getAllPosts();
const postEntries: MetadataRoute.Sitemap = posts
.filter((post) => !post.draft && !post.noindex)
.map((post) => ({
url: `${ORIGIN}/blog/${post.slug}/`, // Match trailingSlash setting!
lastModified: new Date(post.updatedAt ?? post.publishedAt),
}));
return [
{ url: `${ORIGIN}/`, lastModified: new Date("2026-11-02") },
...postEntries,
];
}
04 / REDIRECT STATUS CODES
The accidental 307 Temporary Redirect in middleware.ts
In Next.js middleware, calling NextResponse.redirect(new URL("/new-path", request.url)) defaults to HTTP status 307 Temporary Redirect. When Googlebot encounters a 302 or 307 temporary redirect, it assumes the move is short-lived and often keeps the old URL in the index instead of consolidating signals to the destination URL.
Whenever a redirect in middleware.ts is permanent (such as normalizing uppercase paths, stripping legacy prefixes, or redirecting old blog slugs), pass { status: 308 } or { status: 301 } explicitly, or define the redirect in next.config.ts with permanent: true.
05 / CLOUDFLARE PAGES & VERCEL PREVIEWS
Preventing staging and preview domains from competing with production
When you deploy a Next.js or static site to Cloudflare Pages (*.pages.dev) or Vercel (*.vercel.app), every branch and commit generates a publicly reachable preview URL. If Googlebot discovers a link to your project-name.pages.dev subdomain, it can index the preview host alongside your custom domain.
Protect your canonical domain with two layers:
Hardcode or strictly validate your production canonical origin: Never derive your <link rel="canonical"> host dynamically from the incoming request’s `Host` header on public static pages; otherwise, a request to `project.pages.dev/pricing` will emit a self-referencing canonical for `project.pages.dev`!
Send X-Robots-Tag: noindex on non-production hosts: Configure your hosting headers or middleware so any hostname other than your canonical production domain returns `X-Robots-Tag: noindex, nofollow`.
Honest boundaries & code review safety
Always verify diffs before merging: Automated SEO fixes in a Next.js repository should never bypass your TypeScript compiler or build step. In Searchbop, proposed metadata updates, JSON-LD blocks, and Markdown article drafts are presented as file diffs and submitted via a GitHub pull request so your CI pipeline validates every change.
Implement app/sitemap.ts with the MetadataRoute.Sitemap type. Emit only published canonical URLs, matching your trailing-slash convention and production origin. Use genuine modification dates rather than setting every entry to the current build time.
import type { MetadataRoute } from 'next';
export default function sitemap(): MetadataRoute.Sitemap {
return [{ url: 'https://example.com/guide/',
lastModified: new Date('2026-11-12') }];
}
This single-route example must be extended with your real published content collection. Fetch the deployed XML and check that each destination returns a successful final response. Reference: Next.js sitemap convention.
nextjs generateMetadata seo
Export metadata from a Server Component route and resolve async params before reading the slug. Validate the content record and return a canonical for that specific page. Set metadataBase to your production HTTPS origin in the root layout when using relative metadata URLs.
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { getPost } from '@/lib/posts'; // implement in your content layer
type Props = { params: Promise<{ slug: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const post = await getPost(slug);
if (!post) notFound();
const url = 'https://example.com/guides/' + encodeURIComponent(slug) + '/';
return { title: post.title, description: post.summary,
alternates: { canonical: url },
openGraph: { title: post.title, description: post.summary,
url, type: 'article' } };
}
The route page must also handle missing content correctly. Check inherited metadata and inspect the rendered response for duplicate titles or an unintended root canonical.
Why isn't my Next.js website showing up on Google?
Inspect the deployed route, not just the React source. Confirm it returns the expected status, contains meaningful content, permits crawling and has no production noindex. Compare its canonical URL with the sitemap and check whether authentication, redirect logic or an empty client render blocks access.
In Search Console inspect the exact route and review the indexed canonical and last crawl. A valid build does not prove indexing, and a live inspection does not guarantee inclusion. If many routes share the problem, fix the template or layout before requesting recrawls individually.
How can I optimize my Next.js app for Google indexing?
Render the important answer and internal links in the route response. Configure route-specific metadata, production canonicals and a sitemap of valid published routes. Keep robots rules and preview noindex settings scoped to the correct environment.
Verify the live response, test representative dynamic routes and inspect them in Search Console. Missing content should follow Next.js not-found handling rather than a friendly error message served as a normal page. Remove duplicates or consolidate them with an appropriate canonical, and retain real modification dates in the sitemap.