Next.js SEO: metadata, sitemap and JSON-LD for a blog

Next.js SEO for a blog: set metadata, a sitemap and JSON-LD so Google understands your posts, plus the stale sitemap trap on Vercel and noindex for previews.

Technical SEO for a Next.js blog has three parts: metadata (title, description, canonical) so Google knows what each page is about, a sitemap so it finds every post, and JSON-LD so it understands that the page is an article. Do you want your blog to be found? Let's try it.

Three things Google needs to know your blog exists

In the previous post, the blog already had a safe writing editor and slim images. But Google does not know it is there, and even if it did, it does not yet have enough information to understand each page. I split the work into three parts, and for each one I show you both the code that builds it and how to check it.

The first part is metadata: the <title> tag, the description, the canonical address and the other language versions (hreflang). The second is the sitemap, an XML file that lists every address so search engines do not have to feel their way along each link. The third is the structured data JSON-LD, a block of data that says plainly "this is a BlogPosting, here is the author, published on this date". One more thing is to keep preview deployments out of the index, because that is easy to get backwards.

One thing to say up front: none of these guarantees a page will reach the top. They only help a search engine understand your page correctly. Good content is still what decides.

So that you can follow along without Next.js, I build the pieces as pure functions that run with Node.js. The idea is exactly the same as the code of this blog; the real blog just calls them from inside Next.js. You need Node.js 22.18 or newer, because from that version Node runs .ts files directly, and nothing else needs to be installed. Create a folder seo-blog with this layout:

Folder layout
seo-blog/
  package.json
  try.ts
  src/ld.ts
  src/sitemap-xml.ts
  src/head.ts
  src/check-seo.ts
package.json
{
  "name": "seo-blog",
  "private": true,
  "type": "module"
}

Metadata: title, description, canonical, hreflang

With Next.js (App Router), you declare metadata by exporting a function generateMetadata in the page, or a metadata object. The framework turns it into tags in the <head>. The full usage is in the metadata documentation of Next.js. I do not copy the syntax here, because what is more worth saying is the two practical traps that I met in this blog.

The first trap: metadata from several levels (layout and page) is merged shallowly, and a duplicate key is replaced, not mixed. The Next.js documentation says this in the part about the merge order. The consequence is that if a post page sets alternates or openGraph, it replaces the layout's object entirely, and everything the layout had put in it (the site name, the language, the RSS path) disappears. In the file src/lib/metadata.ts of the blog there is a dedicated note about this, and the solution is to build the metadata of every page through a single function, pageMetadata, so that no page forgets anything.

The second trap is in the canonical address. If a post can be reached through several addresses (with or without a trailing slash, with a tracking parameter, or an English version next to the Vietnamese one), Google needs to know which address is the main one. You declare it with a <link rel="canonical"> tag, and Google explains the reason here. For a post that has translations, each version points its canonical at itself and lists the other versions with hreflang, as the Google guide on localized versions describes.

To see what this looks like, I wrote a function that builds the <head> part, and a small checker that scores it. The function that builds the <head> takes the information of a page and returns an HTML string. Notice that it escapes every value put into an attribute, because a title with a double quote would break the whole tag:

src/head.ts
// Build the <head> of a post page: what the metadata of Next.js (generateMetadata) finally produces.
import { serializeJsonLd } from "./ld.ts";
import { escapeXml as escapeHtml } from "./sitemap-xml.ts";

export type PageInfo = {
  title?: string;
  description?: string;
  canonical?: string;
  languages?: Record<string, string>;
  noindex?: boolean;
  jsonLd?: object;
};

export function renderHead(page: PageInfo): string {
  const lines: string[] = ['<meta charset="utf-8" />'];
  if (page.title) lines.push(`<title>${escapeHtml(page.title)}</title>`, `<meta property="og:title" content="${escapeHtml(page.title)}" />`);
  if (page.description) lines.push(`<meta name="description" content="${escapeHtml(page.description)}" />`, `<meta property="og:description" content="${escapeHtml(page.description)}" />`);
  if (page.canonical) lines.push(`<link rel="canonical" href="${escapeHtml(page.canonical)}" />`);
  for (const [hreflang, href] of Object.entries(page.languages ?? {})) lines.push(`<link rel="alternate" hreflang="${escapeHtml(hreflang)}" href="${escapeHtml(href)}" />`);
  if (page.noindex) lines.push('<meta name="robots" content="noindex" />');
  if (page.jsonLd) lines.push(`<script type="application/ld+json">${serializeJsonLd(page.jsonLd)}</script>`);
  return lines.join("\n");
}

The two helper functions, escapeXml and serializeJsonLd, are in the two files below. You will see them in the next sections. The checker uses regular expressions to stay short. I state clearly in the file that it is enough for a head that I build myself, but cannot be used to read any HTML from the internet:

src/check-seo.ts
// A quick check of the <head> of a page. It uses regular expressions to stay short: enough for a head that I build myself,
// and not usable for reading any HTML from the internet (for that, use a real HTML parser).
export type Result = { mark: "✓" | "✗"; text: string };

const pick = (html: string, pattern: RegExp) => html.match(pattern)?.[1];

export function checkSeo(head: string): Result[] {
  const results: Result[] = [];
  const record = (passed: boolean, text: string) => results.push({ mark: passed ? "✓" : "✗", text });

  const title = pick(head, /<title>([^<]*)<\/title>/);
  record(title !== undefined && title.length >= 30 && title.length <= 65, title === undefined ? "The <title> tag is missing" : `Title is ${title.length} characters (should be 30–65)`);

  const description = pick(head, /<meta name="description" content="([^"]*)"/);
  record(description !== undefined && description.length >= 120 && description.length <= 160, description === undefined ? "The meta description is missing" : `Description is ${description.length} characters (should be 120–160)`);

  const canonical = head.match(/<link rel="canonical" href="([^"]*)"/g) ?? [];
  record(canonical.length === 1 && /href="https?:\/\//.test(canonical[0]), canonical.length === 0 ? "The canonical is missing" : canonical.length > 1 ? "There is more than one canonical" : "Exactly one canonical, and it is a full URL");

  const hreflang = head.match(/<link rel="alternate" hreflang=/g) ?? [];
  record(hreflang.length === 0 || hreflang.length >= 2, hreflang.length === 1 ? "Only one hreflang: you need at least two (or none)" : `hreflang: ${hreflang.length} links`);

  const ld = [...head.matchAll(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/g)];
  if (ld.length === 0) record(false, "The JSON-LD structured data is missing");
  for (const [, content] of ld) {
    try {
      const data = JSON.parse(content);
      record(typeof data["@type"] === "string", `JSON-LD is valid, @type = ${data["@type"]}`);
    } catch {
      record(false, "The JSON-LD cannot be read (it is not valid JSON)");
    }
  }

  record(!/<meta name="robots" content="[^"]*noindex/.test(head), /noindex/.test(head) ? "The page is noindex: Google will not put it in the results" : "Not noindex");
  return results;
}

The thresholds of 30 to 65 characters for the title and 120 to 160 for the description are conventions I set so they are not cut off on the results page. There is no official number from Google here.

The sitemap, and why the sitemap of this blog once did not update

A sitemap is an XML file that lists the addresses of pages. The Google guide (which I read on 12 November 2026) names a few things worth remembering. Every value in the file must have the special XML characters escaped. Google ignores <priority> and <changefreq>. It only uses <lastmod> when that value always matches the real last change of the page. And one file holds at most 50,000 addresses or 50 MB uncompressed. So my version only has <loc>, <lastmod> and the language links, and leaves out the two ignored tags:

src/sitemap-xml.ts
// A sitemap as XML: one <url> per page, with the other language versions (hreflang) and the date of the last change.
export type SitemapEntry = { url: string; lastModified?: string; languages?: Record<string, string> };

// Every value in XML must be escaped; one unescaped & in a URL breaks the whole file.
export function escapeXml(value: string): string {
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
}

export function buildSitemapXml(entries: SitemapEntry[]): string {
  const urls = entries.map((entry) => {
    const lines = ["<url>", `<loc>${escapeXml(entry.url)}</loc>`];
    for (const [hreflang, href] of Object.entries(entry.languages ?? {})) {
      lines.push(`<xhtml:link rel="alternate" hreflang="${escapeXml(hreflang)}" href="${escapeXml(href)}" />`);
    }
    if (entry.lastModified) lines.push(`<lastmod>${escapeXml(entry.lastModified)}</lastmod>`);
    lines.push("</url>");
    return lines.join("\n");
  });
  return [
    '<?xml version="1.0" encoding="UTF-8"?>',
    '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">',
    ...urls,
    "</urlset>",
    "",
  ].join("\n");
}

The function escapeXml is the reason an address with an & does not break the whole file. I wrote a test for it in the suite at the end of the post.

Now the real story of this blog, because it shows that a sitemap can also go wrong in ways you do not expect. At first the blog used the standard Next.js way: a file app/sitemap.ts. On Vercel, the version it serves is the one built at deploy time, and it ignores revalidate = 3600. The consequence is that posts published afterwards were not in /sitemap.xml until the next deploy, while rss.xml, an ordinary route handler with the same configuration, kept updating normally. That is the content of commit 7a06c11 of 10 November 2026 in the project. The first fix was to move the sitemap to a route handler at app/sitemap.xml/route.ts.

But it still did not update. The commit 00d85b6 from the same day explains: Next.js treats every route placed at /sitemap.xml as a metadata route, no matter how the file is written, so on production it is still served as a static file. The final fix was to serve the handler at a different address, /sitemap-all.xml, and then use rewrites in next.config.ts so that the public address /sitemap.xml (the one already in robots.txt and in Search Console) stays the same:

next.config.ts (excerpt from the Tech Notes blog)
// The sitemap lives at /sitemap-all.xml (see that route) and keeps its public address.
async rewrites() {
  return [{ source: "/sitemap.xml", destination: SITEMAP_ROUTE }];
},

The lesson I take from it: a bug like this does not show up when you test on your own machine, because it only happens on Vercel after a new post is published. So I wrote a test so it does not come back. The test checks two things: the public address is rewritten to an address that is not a metadata route, and no file is left at exactly the path /sitemap.xml. For a sitemap, in my view, what is most worth checking is not the content of the file, but whether it really changes after you publish a post in the real environment.

JSON-LD: tell the machine this is an article

JSON-LD is a block of JSON that describes the page with the vocabulary of schema.org. The JSON-LD guide of Next.js recommends placing it in a <script type="application/ld+json"> tag in the layout or the page. For an article, the suitable type is BlogPosting, and the fields I use are the headline, the description, the publish date, the modified date, keywords, the author and the publisher. The Google documentation on structured data for articles describes the fields that are used.

src/ld.ts
// JSON-LD (schema.org) for a blog post: pure functions that return objects, so they can be tested. Same idea as src/lib/structured-data.ts of the Tech Notes blog.

/** The string to put inside <script type="application/ld+json">. It replaces "<" with < so the content can never close the script tag. */
export function serializeJsonLd(data: object): string {
  return JSON.stringify(data).replace(/</g, "\\u003c");
}

export type Crumb = { name: string; url: string };

export function breadcrumbLd(crumbs: Crumb[]) {
  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: crumbs.map((crumb, index) => ({ "@type": "ListItem", position: index + 1, name: crumb.name, item: crumb.url })),
  };
}

export type Post = {
  title: string;
  description: string;
  url: string;
  publishedAt: string;
  updatedAt?: string;
  tags: string[];
  language: string;
  authorName: string;
  siteName: string;
  siteUrl: string;
};

export function blogPostingLd(post: Post) {
  return {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: post.title,
    description: post.description,
    datePublished: post.publishedAt,
    dateModified: post.updatedAt ?? post.publishedAt,
    inLanguage: post.language,
    keywords: post.tags.join(", "),
    mainEntityOfPage: { "@type": "WebPage", "@id": post.url },
    url: post.url,
    author: { "@type": "Person", name: post.authorName },
    publisher: { "@type": "Organization", name: post.siteName, url: post.siteUrl },
  };
}

The function serializeJsonLd is the place where I want you to stop. It calls JSON.stringify and then replaces every < character with <. The Next.js documentation says the same thing: JSON.stringify does not sanitize dangerous strings, so you should replace < with its Unicode form. The reason is the same as in the Markdown story in the post about the safe editor: the title of a post is data entered by the writer, and if it contains </script>, the script tag is closed early and what comes after it runs as ordinary HTML. I try that in the script below, together with scoring two pages and printing the sitemap:

try.ts
// Run: node try.ts. Build the head of a post in two ways and score it; try the sitemap; try JSON-LD when the title contains malicious code.
import { renderHead } from "./src/head.ts";
import { checkSeo } from "./src/check-seo.ts";
import { blogPostingLd, serializeJsonLd } from "./src/ld.ts";
import { buildSitemapXml } from "./src/sitemap-xml.ts";

const SITE = "https://blog.example.com";
const post = {
  title: "Compress images before upload: from 8 MB to 400 KB",
  description: "Compress images before upload for a Next.js blog: shrink to 1600 px, convert to WebP, strip EXIF and GPS. Real measurements and the sideways-photo trap.",
  url: `${SITE}/en/posts/compress-images-before-upload-nextjs-blog`,
  publishedAt: "2026-11-15T08:00:00+07:00",
  tags: ["Next.js", "images", "WebP"],
  language: "en",
  authorName: "The author",
  siteName: "Sample blog",
  siteUrl: SITE,
};
const VI_VERSION = `${SITE}/bai-viet/nen-anh-truoc-khi-upload`;

const printResults = (name: string, head: string) => {
  console.log(`--- ${name}`);
  for (const item of checkSeo(head)) console.log(`${item.mark} ${item.text}`);
};

// Way 1: only a title, like a page that was just created and nobody thought about SEO yet.
printResults("A page with only a title", renderHead({ title: "A post" }));

// Way 2: complete metadata and JSON-LD, like what generateMetadata plus a JSON-LD <script> tag produce.
printResults("A page with full metadata and JSON-LD", renderHead({
  title: post.title,
  description: post.description,
  canonical: post.url,
  languages: { en: post.url, vi: VI_VERSION, "x-default": post.url },
  jsonLd: blogPostingLd(post),
}));

console.log("\n--- Sitemap");
console.log(buildSitemapXml([
  { url: post.url, lastModified: post.publishedAt, languages: { en: post.url, vi: VI_VERSION } },
  { url: `${SITE}/en/topics/web-thuc-chien` },
]));

// The title is chosen by the writer: if it contains </script>, a naive serialization lets it escape from the tag.
console.log("--- JSON-LD when the title contains malicious code");
const doc = blogPostingLd({ ...post, title: 'Post </script><script>alert("xss")</script>' });
const naive = `<script type="application/ld+json">${JSON.stringify(doc)}</script>`;
const safe = `<script type="application/ld+json">${serializeJsonLd(doc)}</script>`;
const countTags = (html: string) => (html.match(/<script/g) ?? []).length;
console.log(`Plain JSON.stringify: ${countTags(naive)} <script> tags in the result`);
console.log(`serializeJsonLd:      ${countTags(safe)} <script> tag in the result`);
Try it
node try.ts
Output
--- A page with only a title
✗ Title is 6 characters (should be 30–65)
✗ The meta description is missing
✗ The canonical is missing
✓ hreflang: 0 links
✗ The JSON-LD structured data is missing
✓ Not noindex
--- A page with full metadata and JSON-LD
✓ Title is 50 characters (should be 30–65)
✓ Description is 152 characters (should be 120–160)
✓ Exactly one canonical, and it is a full URL
✓ hreflang: 3 links
✓ JSON-LD is valid, @type = BlogPosting
✓ Not noindex

--- Sitemap
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
<url>
<loc>https://blog.example.com/en/posts/compress-images-before-upload-nextjs-blog</loc>
<xhtml:link rel="alternate" hreflang="en" href="https://blog.example.com/en/posts/compress-images-before-upload-nextjs-blog" />
<xhtml:link rel="alternate" hreflang="vi" href="https://blog.example.com/bai-viet/nen-anh-truoc-khi-upload" />
<lastmod>2026-11-15T08:00:00+07:00</lastmod>
</url>
<url>
<loc>https://blog.example.com/en/topics/web-thuc-chien</loc>
</url>
</urlset>

--- JSON-LD when the title contains malicious code
Plain JSON.stringify: 2 <script> tags in the result
serializeJsonLd:      1 <script> tag in the result

The first part shows that a freshly created page (with only the title "A post") fails almost every item: the title is too short, and the description, the canonical and the JSON-LD are missing. The second part is the same kind of page with full information, and it passes everything. The line hreflang: 0 links on the first page counts as a pass, because a page with no translation does not need hreflang, and the checker only complains when there is exactly one link, since hreflang needs at least two versions to mean anything. The sitemap part is a valid XML file with one post that has a Vietnamese version and one topic page. The last part is the most important result: with a title that contains </script><script>alert("xss")</script>, the naive way gives two <script> tags in the HTML (the second is the code of an attacker), while serializeJsonLd gives only one. The address blog.example.com and the sample post are illustrative.

After you deploy for real, you check the JSON-LD with the tools of Google itself: the Rich Results Test, or the Schema Markup Validator (both are mentioned by the Next.js documentation). My checker only verifies valid JSON and the presence of @type. It does not replace those two tools.

A preview must never be indexed

One more small thing with a large consequence. Every pull request of this blog has a preview on Vercel with its own address. If Google indexes them, you get many copies of the same post at strange addresses, and draft content can leak into the search results. So the convention of the project (written in AGENTS.md) is that a preview must be noindex, and only the production build may be indexed. The code that does it is very short. The function isIndexable in src/lib/site.ts returns true only when the environment variable VERCEL_ENV equals production, and robots.ts uses it to choose the rules:

src/app/robots.ts (excerpt from the Tech Notes blog)
export default function robots(): MetadataRoute.Robots {
  if (!isIndexable()) {
    return { rules: { userAgent: "*", disallow: "/" } };
  }
  return {
    rules: { userAgent: "*", allow: "/", disallow: "/tim-kiem" },
    sitemap: absoluteUrl("/sitemap.xml"),
  };
}

Its test checks one valuable thing: only the value production allows indexing, while preview, development and an empty string are all blocked. The safe default here is "do not index", and I must switch it on for production on purpose, instead of indexing by default and remembering to switch it off for previews. If I forget to switch it on, the page is just not on Google yet, but if I forget to switch it off, draft content leaks, so I chose the failure that is easier to repair.

Tests for the SEO functions

Eight tests cover the functions in this post (XML escaping and JSON-LD, the default for dateModified, the position of breadcrumbs, a sitemap with &, a single hreflang and noindex being flagged, and broken JSON-LD being flagged). They run with the test runner that ships with Node, so there is nothing to install:

Run the tests (in the folder with the files)
node --test src/seo.test.ts
Output
# tests 8
# pass 8
# fail 0

You can write them yourself from the rules above, because every function is small.

What about sharing on Facebook?

By now Google has everything it needs to understand and find the posts. But there is one more place where people find your post: when someone pastes the link into Facebook, Zalo or Slack. The app then does not show search results but a preview card, and a preview card needs a picture. How to make a share image for every post without designing it by hand is the topic of the next posts.

You can follow the whole series at Build a blog with Next.js + Supabase. If you are preparing for interviews, the questions about Next.js, React and security are in the interview question bank.

Get the next post by email.

One email a week, only when there is something worth reading. No spam.