VENNStart
Guide

Fixing URLs, hreflang and sitemaps on my multilingual Next.js site

SEO mistakes I made on vennee.dev: a locale read from a cookie and hreflang aimed at a query string, plus metadata and a sitemap that didn't match.

Lê Anh Tuấn4 min read

When I built vennee.dev's locale routing, the site had English, Vietnamese, French and Russian versions, and the blog had English and Vietnamese. The public site is temporarily English-only now. These examples describe the multilingual setup.

The UI switched languages fine. The layout's metadata, though, declared hreflang like "vi-VN": "/?lang=vi", a parameter the server never read, and the projects page took its locale from a cookie. Crawlers saw English only for four months. The URLs, canonicals, hreflang and sitemap have to agree on which versions exist.

Give each language a crawlable URL

Each language version needs its own URL with the language in the path and a self-referencing canonical. Hreflang is a reciprocal cluster of absolute URLs: each version lists itself, every other version and x-default (the English root on my site).

On my first version, /projects read a NEXT_LOCALE cookie, and every ?lang= "alternate" returned the same HTML. Googlebot usually crawls without cookies or an Accept-Language header, so it only ever saw English.

Put the language in the path with proxy

I went with the "as needed" prefix, with English at the root (/projects), other languages prefixed (/vi/projects). All pages live under app/[locale]/, and proxy.ts (Next.js 16, formerly middleware.ts) rewrites unprefixed URLs to the English segment.

// src/proxy.ts
import { NextResponse, type NextRequest } from "next/server";

const LOCALES = ["en", "vi", "fr", "ru"];
const DEFAULT_LOCALE = "en";

export default function proxy(req: NextRequest) {
  const { pathname } = req.nextUrl;
  const locale = LOCALES.find((l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`));

  if (locale === DEFAULT_LOCALE) {
    // /en/... duplicates /...: fold it into the root, permanently.
    const url = req.nextUrl.clone();
    url.pathname = pathname.slice(DEFAULT_LOCALE.length + 1) || "/";
    return NextResponse.redirect(url, 308);
  }

  if (!locale) {
    // Serve English at the root without changing the visible URL.
    return NextResponse.rewrite(new URL(`/${DEFAULT_LOCALE}${pathname}`, req.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico|.*\\..*).*)"],
};

NextResponse.redirect defaults to 307, and my first /en redirect never passed a status. A 307 is temporary and doesn't give Google the same canonicalization signal as a permanent redirect. Now it passes 308.

I still redirect / to the language saved in the cookie, only on the root and on the default 307, because it depends on who's asking. Crawlers get the English root.

On next-intl, localePrefix: "as-needed" gives the same scheme, but its middleware also sends hreflang in a Link header by default (alternateLinks). If you set alternates in metadata too, keep both in agreement or switch one off.

Every URL comes out of one file

Canonicals, hreflang, the sitemap, Open Graph and JSON-LD all print URLs, and separately built ones drift. Mine come from one module:

// src/lib/seo.ts
export const SITE_URL = (process.env.NEXT_PUBLIC_SITE_URL || "https://example.com").replace(/\/$/, "");

export const LOCALES = ["en", "vi", "fr", "ru"] as const;
export type Locale = (typeof LOCALES)[number];

const PREFIX: Record<Locale, string> = { en: "", vi: "/vi", fr: "/fr", ru: "/ru" };

export function localizedPath(locale: Locale, path = "") {
  return `${PREFIX[locale]}${path}` || "/";
}

export function absoluteUrl(path = "") {
  return path === "/" ? SITE_URL : `${SITE_URL}${path}`;
}

/** hreflang map for one page, limited to the locales it exists in. */
export function languageAlternates(path: string, locales: readonly Locale[] = LOCALES, absolute = false) {
  const href = (l: Locale) => (absolute ? absoluteUrl(localizedPath(l, path)) : localizedPath(l, path));
  return {
    ...Object.fromEntries(locales.map((l) => [l, href(l)])),
    ...(locales.includes("en") ? { "x-default": href("en") } : {}),
  };
}

SITE_URL has to be the host you serve, or every canonical and sitemap entry points at a redirect. An older project of mine fell back to http://localhost:3000 in sitemap.ts, and on any environment missing the variable the sitemap handed Google a list of localhost links.

The locales parameter is for partial translations. The blog has no fr, so listing it would point Google at a 404.

The [locale] layout sets metadataBase: new URL(SITE_URL), so relative URLs in alternates and openGraph come out absolute. Each page returns complete metadata through one builder:

import type { Metadata } from "next";

const OG_LOCALE: Record<Locale, string> = { en: "en_US", vi: "vi_VN", fr: "fr_FR", ru: "ru_RU" };

export function buildMetadata(input: {
  locale: Locale; path: string; title: string; description: string; locales?: readonly Locale[];
}): Metadata {
  const { locale, path, title, description, locales = LOCALES } = input;
  const url = localizedPath(locale, path);
  const images = [{ url: "/og.png", width: 1200, height: 630 }];

  // openGraph and twitter replace the parent's object, so send the full set.
  return {
    title: { absolute: title },
    description,
    alternates: { canonical: url, languages: languageAlternates(path, locales) },
    openGraph: {
      type: "website", url, siteName: "Example", title, description, images,
      locale: OG_LOCALE[locale],
      alternateLocale: locales.filter((l) => l !== locale).map((l) => OG_LOCALE[l]),
    },
    twitter: { card: "summary_large_image", title, description, images: ["/og.png"] },
  };
}

Next.js merges metadata shallowly. A nested object like openGraph, twitter or robots set in a page replaces the layout's object entirely. My early projects page set its own openGraph with a title and description and quietly dropped the layout's locale and siteName. alternates is nastier. A canonical set in the layout is inherited by every child page that doesn't set its own, which canonicalizes all of them to the home page without a warning.

The metadata needs translating too. My projects page first returned one English title for all four locales, which looks like a duplicate. Now there's a typed Record<Locale, Record<Page, { title, description }>> table, with titles under 60 characters and descriptions around 155. The breadcrumb names and the JSON-LD Person description come from it as well.

The first fix dropped ?lang= but kept en-US and vi-VN, targeting one country per version, which I didn't mean. The codes are now bare languages like fr. Google accepts ISO 639-1 language codes, optionally with a region, but not a region alone. Open Graph uses the vi_VN format, so I keep two separate maps.

Sitemap with hreflang alternates

Each entry's alternates.languages in app/sitemap.ts becomes <xhtml:link rel="alternate" hreflang="...">:

// app/sitemap.ts
import type { MetadataRoute } from "next";

const PAGES = ["", "/projects", "/contact"];

export default function sitemap(): MetadataRoute.Sitemap {
  const pages = LOCALES.flatMap((locale) =>
    PAGES.map((path) => ({
      url: absoluteUrl(localizedPath(locale, path)),
      alternates: { languages: languageAlternates(path, LOCALES, true) },
    })),
  );

  const posts = getPostSlugs().flatMap((slug) => {
    const locales = getPostLocales(slug); // e.g. ["en", "vi"]
    const path = `/blog/${slug}`;
    return locales.map((locale) => ({
      url: absoluteUrl(localizedPath(locale, path)),
      lastModified: getPost(locale, slug)?.date,
      alternates: { languages: languageAlternates(path, locales, true) },
    }));
  });

  return [...pages, ...posts];
}

metadataBase doesn't apply to the sitemap. That's what absolute = true is for.

My first sitemap set lastModified: new Date() on every URL, so each deploy stamped every page with the build time. Google only uses lastmod when it's consistently accurate and ignores changefreq and priority. Static pages now have no lastModified, and posts use their real date.

JSON-LD, OG images and snippets

The Next.js JSON-LD guide renders a <script type="application/ld+json"> tag with < escaped. I keep one site-wide graph in the layout and reference its nodes by @id:

const PERSON_ID = `${SITE_URL}/#person`;

export function siteGraph(locale: Locale) {
  return {
    "@context": "https://schema.org",
    "@graph": [
      { "@type": "WebSite", "@id": `${SITE_URL}/#website`, url: SITE_URL,
        name: "Example", inLanguage: LOCALES, publisher: { "@id": PERSON_ID } },
      { "@type": "Person", "@id": PERSON_ID, name: "Jane Doe", url: SITE_URL,
        jobTitle: JOB_TITLE[locale], sameAs: ["https://github.com/example"] },
    ],
  };
}

export function JsonLd({ data }: { data: Record<string, unknown> }) {
  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(data).replace(/</g, "\\u003c") }}
    />
  );
}

The home page is a ProfilePage with mainEntity: { "@id": PERSON_ID }, inner pages get WebPage and BreadcrumbList, and posts are BlogPosting with the same @id as author. Check CMS dates first. On a client project, a malformed date string made toISOString() throw a RangeError. Without a trustworthy date, leave the field out.

Per-post share images use opengraph-image.tsx in app/[locale]/blog/[slug]/. File-based metadata takes priority, and the builder passes no images for that route.

The home page loader's text comes first in the HTML and could end up as the snippet. The loader's root div has data-nosnippet, which has to be in the server-rendered HTML.

Permanent redirects, checked with curl

A moved URL needs one permanent redirect. Google treats 301 and 308 as permanent and 302, 303 and 307 as temporary. In Next.js, permanent: true in next.config and permanentRedirect() return 308. redirect() in a Server Component, permanent: false and NextResponse.redirect() without a status all return 307. Fixed path changes go in next.config redirects. Then update canonicals, the sitemap and internal links to the final URL. A much bigger URL move is in keeping every old URL on a car rental site.

Check status codes with curl -I, because the browser hides them. After a change like this I read the rendered HTML and the sitemap before touching the language switcher, since the UI never showed those ?lang= links. I don't have Search Console numbers from before and after. The site now declares its versions correctly, and I can't say yet whether rankings moved.

  • Next.js
  • SEO
  • i18n
  • hreflang
  • App Router
  • Structured data

I'm Tuấn (Venn), a web developer in Ho Chi Minh City. I mostly build Next.js sites and web apps, and I take freelance work.

Work with me

More posts

  1. 01Guide4 min read

    Deploying Next.js and NestJS to AWS EC2 with Docker Compose

    How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.

  2. 02Guide4 min read

    How I store OAuth tokens for social media APIs in NestJS

    OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.

  3. 03vennee.dev3 min read

    llms.txt on my Next.js site, and now Lighthouse grades it

    vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.