In part 1 we put Next.js + Strapi on a VPS. Now let's make Google actually understand the site.

Headless setups are fast, but they're also easy to get wrong for SEO: titles hardcoded in components, no canonical tags, sitemaps that go stale, and missing pages that return 200 instead of 404. We've fixed all of these on client sites — here's the setup we now start every project with.

What we'll cover:

  1. An SEO component in Strapi so editors control metadata
  2. generateMetadata — titles, descriptions, canonicals, Open Graph
  3. A dynamic sitemap.xml and robots.txt
  4. JSON-LD schema markup
  5. Real 404s, and keeping staging out of Google

All examples use Next.js 15 (App Router) and Strapi 5.

1. Give editors an SEO component in Strapi

Don't generate titles from code. Editors (and SEO people) need to control them per page.

In Strapi's Content-Type Builder, create a reusable component shared.seo:

Field Type Notes
metaTitle Text Aim for ~50–60 characters
metaDescription Text (long) Aim for ~150–160 characters
metaImage Media (single) Open Graph image, 1200×630
canonicalURL Text Optional override
noIndex Boolean Default false

Add it to every content type that becomes a page (article, page, service…) as a single component named seo.

Fetch it with populate, using the helper from part 1:

// lib/articles.ts import { strapi } from './strapi'; export async function getArticle(slug: string) { const qs = new URLSearchParams({ 'filters[slug][$eq]': slug, 'populate[seo][populate]': 'metaImage', 'populate[cover]': 'true', }); const res = await strapi<{ data: Article[] }>(`articles?${qs}`, 'article'); return res.data[0] ?? null; } 

Because the fetch is tagged article, the Strapi webhook from part 1 refreshes metadata the moment an editor hits publish.

2. generateMetadata: one function, all the tags

First, set metadataBase once in the root layout so every relative URL becomes absolute:

// app/layout.tsx import type { Metadata } from 'next'; export const metadata: Metadata = { metadataBase: new URL('https://example.com'), title: { default: 'Example', template: '%s' }, }; 

Then in the article route:

// app/blog/[slug]/page.tsx import type { Metadata } from 'next'; import { notFound } from 'next/navigation'; import { getArticle } from '@/lib/articles'; type Props = { params: Promise<{ slug: string }> }; const CMS = 'https://cms.example.com'; export async function generateMetadata({ params }: Props): Promise<Metadata> { const { slug } = await params; const article = await getArticle(slug); if (!article) return {}; const seo = article.seo ?? {}; const title = seo.metaTitle || article.title; const description = seo.metaDescription || article.excerpt; const image = seo.metaImage?.url ? `${CMS}${seo.metaImage.url}` : undefined; return { title, description, alternates: { canonical: seo.canonicalURL || `/blog/${slug}`, }, robots: seo.noIndex ? { index: false, follow: true } : undefined, openGraph: { type: 'article', title, description, url: `/blog/${slug}`, publishedTime: article.publishedAt, modifiedTime: article.updatedAt, images: image ? [{ url: image, width: 1200, height: 630 }] : undefined, }, twitter: { card: 'summary_large_image', title, description }, }; } 

A few things that matter here:

  • Always fall back. If an editor leaves metaTitle empty, use the article title. Empty <title> tags are surprisingly common in headless sites.
  • Canonical on every page. It's your defense against duplicate URLs created by query strings (?utm_source=…, ?page=2, tracking params).
  • noIndex is per page. Thank-you pages, internal search results, thin tag pages — let editors switch them off without a deploy.

Next.js deduplicates identical fetch calls in the same render, so calling getArticle in both generateMetadata and the page component doesn't hit Strapi twice.

Multi-language sites

If you use Strapi's i18n plugin, add hreflang alternates:

alternates: { canonical: `/vi/blog/${slug}`, languages: { vi: `/vi/blog/${slug}`, en: `/en/blog/${enSlug}`, 'x-default': `/en/blog/${enSlug}`, }, }, 

Each language version must point to all the others — including itself.

3. Real 404s (no soft 404s)

This one is easy to miss. If a slug doesn't exist and your page renders an empty layout, the server returns 200 OK with no content. Google calls that a soft 404, and a site full of them looks low-quality.

export default async function ArticlePage({ params }: Props) { const { slug } = await params; const article = await getArticle(slug); if (!article) notFound(); // proper 404 status return <Article data={article} />; } 

Also pre-render known slugs at build time:

export async function generateStaticParams() { const res = await strapi<{ data: { slug: string }[] }>( 'articles?fields[0]=slug&pagination[pageSize]=100', 'article' ); return res.data.map((a) => ({ slug: a.slug })); } 

4. A sitemap that never goes stale

Next.js generates /sitemap.xml from app/sitemap.ts. The catch: Strapi's REST API paginates (100 items per page by default), so a naive single request silently drops everything after item 100.

// app/sitemap.ts import type { MetadataRoute } from 'next'; import { strapi } from '@/lib/strapi'; const SITE = 'https://example.com'; type Row = { slug: string; updatedAt: string; seo?: { noIndex?: boolean } }; async function getAll(collection: string, tag: string) { const rows: Row[] = []; let page = 1; let pageCount = 1; do { const res = await strapi<{ data: Row[]; meta: { pagination: { pageCount: number } } }>( `${collection}?fields[0]=slug&fields[1]=updatedAt&populate[seo][fields][0]=noIndex` + `&pagination[page]=${page}&pagination[pageSize]=100`, tag ); rows.push(...res.data); pageCount = res.meta.pagination.pageCount; page++; } while (page <= pageCount); return rows.filter((r) => !r.seo?.noIndex); } export default async function sitemap(): Promise<MetadataRoute.Sitemap> { const articles = await getAll('articles', 'article'); return [ { url: SITE, lastModified: new Date() }, { url: `${SITE}/blog`, lastModified: new Date() }, ...articles.map((a) => ({ url: `${SITE}/blog/${a.slug}`, lastModified: new Date(a.updatedAt), })), ]; } 

Why this works well:

  • noIndex pages are excluded. A sitemap should only list URLs you want indexed — listing noindexed pages sends Google mixed signals.
  • lastModified comes from Strapi's updatedAt, so it's real, not "now" on every build.
  • Same article cache tag, so publishing a post updates the sitemap too.

Strapi 5's REST API returns only published entries by default, so drafts don't leak into the sitemap.

5. robots.txt — and keep staging out of Google

// app/robots.ts import type { MetadataRoute } from 'next'; export default function robots(): MetadataRoute.Robots { const isProd = process.env.SITE_ENV === 'production'; if (!isProd) { return { rules: { userAgent: '*', disallow: '/' } }; } return { rules: { userAgent: '*', allow: '/', disallow: ['/api/'] }, sitemap: 'https://example.com/sitemap.xml', }; } 

Set SITE_ENV=production only on the production server. We've seen more than one staging domain end up in Google results — duplicate content of the live site, sometimes outranking it.

robots.txt blocks crawling, not indexing. For staging, HTTP basic auth in Nginx is the stronger option. Use both if you can.

6. JSON-LD schema markup

Structured data helps Google understand what a page is. For blog posts, Article + BreadcrumbList is a solid baseline:

// components/ArticleJsonLd.tsx const SITE = 'https://example.com'; export function ArticleJsonLd({ article }: { article: Article }) { const url = `${SITE}/blog/${article.slug}`; const data = { '@context': 'https://schema.org', '@graph': [ { '@type': 'Article', headline: article.title, description: article.seo?.metaDescription || article.excerpt, image: article.cover?.url ? [`https://cms.example.com${article.cover.url}`] : undefined, datePublished: article.publishedAt, dateModified: article.updatedAt, author: { '@type': 'Organization', name: 'Example', url: SITE }, mainEntityOfPage: url, }, { '@type': 'BreadcrumbList', itemListElement: [ { '@type': 'ListItem', position: 1, name: 'Home', item: SITE }, { '@type': 'ListItem', position: 2, name: 'Blog', item: `${SITE}/blog` }, { '@type': 'ListItem', position: 3, name: article.title, item: url }, ], }, ], }; return ( <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(data).replace(/</g, '\\u003c'), }} /> ); } 

The .replace(/</g, '\\u003c') matters: CMS content is user input, and without escaping, a </script> inside a title could break out of the tag.

Validate with Google's Rich Results Test before shipping.

7. Small things that add up

  • Image alt from Strapi. Strapi's media library has an alternativeText field — pass it to next/image. Make it required in your editor guidelines.
  • One URL format. Pick trailing slash or not (trailingSlash in next.config) and stick with it. Mixed formats create duplicate URLs.
  • Redirects when slugs change. Editors will rename slugs. Keep old URLs alive with 301 redirects (redirects() in next.config, or a redirect collection in Strapi read by middleware).
  • Submit the sitemap in Google Search Console and check the Pages report after launch.

Pre-launch SEO checklist

Check How
Every page has a unique <title> and description View source / crawl with Screaming Frog
Canonical present and absolute View source
Missing slugs return 404 curl -I https://example.com/blog/does-not-exist
sitemap.xml lists all published pages, no noindexed ones Open it, compare count with Strapi
robots.txt correct on prod, blocking on staging Open both
JSON-LD valid Rich Results Test
Open Graph image shows Share the link in a chat app
Sitemap submitted Google Search Console

Next in this series: what we learned fixing "Crawled – currently not indexed" on a large batch of URLs.

What's your go-to SEO setup for headless sites? Anything you'd add to the checklist? 👇

I run Tấn Phát Digital, a web design & SEO agency in Ho Chi Minh City, Vietnam.