Localisation9 min read

How to Implement Locale Routing With Next.js and a Headless CMS

A French visitor clicks the language switcher on /en/blog/pricing-update and lands on /fr/blog/pricing-update, which returns a 404 because the French article lives at /fr/blog/mise-a-jour-des-tarifs.

Published November 15, 2026

A French visitor clicks the language switcher on /en/blog/pricing-update and lands on /fr/blog/pricing-update, which returns a 404 because the French article lives at /fr/blog/mise-a-jour-des-tarifs. To implement locale routing with Next.js and a headless CMS, put every route under app/[lang], detect the locale in Proxy, and pass lang into the content query. In Sanity, that query is *[_type == "post" && language == $lang && slug.current == $slug], and coalesce() handles missing translations.

The cost goes beyond one broken link. Mismatched slugs break switchers, wrong hreflang tags send search engines to the wrong language, missing translations show up as empty pages, and editors can't check the French page before it goes live. Each of these problems usually comes from a routing layer and a content layer that use different definitions of a locale.

Routing is the easy part. The URL, the query, the schema, and the preview all have to agree on which languages exist and how one document relates to its translations. This guide treats the content schema as the source of truth for routes, then works outward to Proxy, static params, metadata, the language switcher, and per-locale preview.

Should you use locale subpaths, domains, or subdomains in Next.js?

For most Next.js projects, locale subpaths (/fr/products) are the best default because one deployment, one domain, and one App Router tree serve every language. The Next.js internationalization guide names two routing strategies, sub-path and domain (my-site.fr/products). Once the request reaches your app, both feed the same [lang] segment.

Subpaths keep operations simple. You get one TLS certificate, one analytics property, one sitemap index, and search authority that builds up on a single domain. The tradeoff is that the locale appears in every URL, so every internal link, canonical tag, and redirect has to carry it. Teams that forget this ship links that drop the prefix and send users back to the default language.

Domains (example.fr, example.de) suit organizations whose legal entities, pricing, or legal copy differ by market. Domains signal country targeting clearly, but each one needs its own DNS, certificates, and usually its own search console property. Subdomains (fr.example.com) fall between the two options. In Next.js, domain and subdomain routing both work the same way: Proxy reads the host header and rewrites the request internally to /fr/..., so the App Router still sees a [lang] segment. That rewrite is the key design decision. Whatever public URL scheme you choose, keep one internal route tree keyed by locale.

Language and market are different things. A Swiss site may need de-CH, fr-CH, and it-CH on one domain. A Spanish-language business may serve es-ES and es-MX with different prices. If you put the market in the domain and the language in the subpath, define that rule once in a shared locale config and import it in Proxy, generateStaticParams, and the sitemap. The content backend should hold the same list of language codes, so a document's language field always maps to a route that exists.

How does the Next.js App Router handle a [lang] segment and locale detection?

The App Router handles locales through a dynamic [lang] segment at the top of the app directory, and Proxy decides which [lang] each request gets. In Next.js 16, middleware.ts was renamed proxy.ts and its exported function is now proxy. Vercel's documentation says Proxy runs in the Node.js runtime. Set it up in this order:

1. Define a locales array and a default locale in one shared module.
2. Move every special file in app/ under app/[lang], with the root layout at app/[lang]/layout.tsx, so the router forwards lang to every layout and page.
3. In proxy.ts, check whether the pathname already starts with a supported locale. If it doesn't, negotiate one from the Accept-Language header (the official guide uses @formatjs/intl-localematcher and negotiator) and redirect, so /products becomes /en-US/products.
4. In each page, read const { lang } = await params, typed with the PageProps<'/[lang]'> helper.
5. Guard with hasLocale() and call notFound() for unsupported values, so /xx/products returns a 404 instead of an empty page.

Two details often trip teams up. First, detection should run only when the URL has no locale. If a user deliberately chose /fr, Accept-Language must not override that choice, so store it in a cookie and read the cookie before negotiating. Second, server utilities deep in the tree often need the locale for formatting or queries. next/root-params exports a lang getter, so a data-fetching helper can read the current locale without passing lang through every component.

Keep Proxy thin. It should choose the locale and then redirect or rewrite, without fetching content. Fetching translations in Proxy adds latency to every matched request, including assets that a loose matcher forgot to exclude. Put the content query in the page, where lang is already a typed param and the fetch can use the page's normal data-loading and caching path.

Should localization be field-level or document-level in the schema?

Field-level localization keeps every language inside one document. Document-level localization creates a separate document for each language. Choose based on how each content type gets published. Sanity localizes content by storing language data as a field value, and you choose the strategy per schema type, so one project can use both.

Field-level localization fits documents that combine shared fields with translated ones. A product has one price, one SKU, and one image, but a title and description in each language. With the sanity-plugin-internationalized-array plugin, each translated field becomes an array of {_key, language, value} items, and the plugin works with any field type. All languages publish together, which is what you want when a price change must ship everywhere at once.

Document-level localization fits long-form content, especially Portable Text bodies, pages that exist in only one locale, and translations that arrive weeks after the original. The @sanity/document-internationalization plugin sets a language field on each document and creates a translation.metadata document that references every translation. Each language publishes on its own schedule, so the German article can go live while the Japanese one is still in review. Each language also gets its own slug, which matters for routing.

This per-type choice is where Sanity's role as the AI Content Operating System shows up in practice. The schema reflects how your business actually publishes, so you don't have to force one localization strategy on every content type. Products can use field-level localization and articles can use document-level localization in the same Content Lake, and the same GROQ queries both.

A working rule: if two language versions must never be out of sync, use field-level. If they have different lifecycles, different slugs, or different editors, use document-level. Decide this before you write routes, because the strategy determines where the slug lives.

â„šī¸

Arrays keep attribute counts flat

An object pattern such as title.en and title.fr adds a new dataset attribute for every language. The internationalized-array pattern only ever creates title[], title[]._key, title[].language, and title[].value. That matters because each Sanity dataset has an attribute limit of 2k on the Free plan and 10k on Growth, and a site with many locales and fields can hit the limit faster than expected.

How do you query localized content with a fallback to the default language?

Pass the locale to the query as a parameter and let the query fall back to the default language when a translation is missing. In GROQ, coalesce() returns the first non-null value from its arguments, so the fallback order is written into the query and resolved in a single round trip.

For field-level content, the Sanity docs show this projection: "title": coalesce(title[language == $language][0].value, title[language == $baseLanguage][0].value, "Missing translation"). The filter in brackets selects the array item for the requested language, [0].value unwraps it, and the final string is a visible placeholder that makes gaps obvious during QA. In a Next.js page, $language comes from the [lang] param and $baseLanguage comes from your shared locale config. Because both are variables, the same query string works for every locale.

If you're upgrading an older project, check the plugin version. In internationalized-array v5, the language moved out of _key and into a language field, so queries like title[_key == "en"] must become title[language == "en"]. Old queries fail quietly by returning null, which coalesce() then hides behind the fallback, so search the codebase for _key filters after upgrading.

For document-level content, the query filters on the language field directly: *[_type == "post" && language == $lang && slug.current == $slug][0]. At this level, fallback is a routing decision, not a projection. When no French document exists, you have three honest options: return notFound(), redirect to the default-language URL, or render the default-language document with a visible notice. Serving English content at a /fr URL with no signal to readers or search engines confuses both, so pick one behavior and apply it everywhere.

Keep the fallback language separate from the user's preferred language. A Swiss French reader might reasonably fall back to fr before en. Because the order lives in coalesce() arguments, you can pass a per-locale fallback chain without changing the schema.

How do you generate localized slugs, static params, and hreflang from CMS data?

Generate localized routes by querying every published language and slug pair from the content backend, then reusing that data for static params, metadata, and the sitemap. If the schema uses document-level localization, each document already holds its own language and slug.current, so the route table falls out of one query.

For generateStaticParams in app/[lang]/blog/[slug]/page.tsx, fetch something like *[_type == "post" && defined(slug.current)]{ "lang": language, "slug": slug.current }. Next.js builds only the pairs that actually exist. A post translated into three of five languages produces three routes, with no empty pages for the other two. With field-level localization, slugs are usually shared or stored as one array item per language, and you expand them in the projection the same way you expand titles.

Hreflang alternates tell search engines which URLs are translations of each other. In generateMetadata, the alternates.languages object outputs <link rel="alternate" hreflang> tags. Fill it from the same translation data the page already loads. With document-level localization, project the sibling translations through the translation.metadata document and map each one to its locale and path. The French post's alternates then point to the German post's real slug, not a guessed one. Include the current page in its own alternate set, and add an x-default entry that points to your default-locale URL.

A localized sitemap needs the same data. Build app/sitemap.ts from the query that feeds generateStaticParams so the two can't drift apart, and attach each URL's language alternates before you ship. The Next.js sitemap reference documents the exact field shape. Using a single query for routes, metadata, and the sitemap removes a common class of bugs, such as a sitemap that lists a URL the build never generated.

Treat slugs as content. Translators should localize slugs alongside titles, and the schema should validate that slug.current is unique within each language, not across all of them. Two languages can legitimately share a slug like "faq".

How do you build a language switcher that links to the translated document?

A language switcher should link to each translation's own URL, built from the translated document's language and slug, and should never reuse the current slug with a different prefix. Swapping /en/ for /fr/ in the current path works only when slugs are identical across languages, and real localized slugs rarely are.

With Sanity's document-level localization, the translation.metadata document already records which documents are translations of each other. The Sanity docs show how to fetch a page and its siblings in one query: *[_type == "lesson" && language == $language]{ title, slug, language, "_translations": *[_type == "translation.metadata" && references(^._id)].translations[].value->{title, slug, language} }. The ^._id refers to the outer document, references() finds the metadata document that points to it, and the -> operator dereferences every translation to return its title, slug, and language. The page and the switcher's data arrive together.

Build the switcher from _translations, not from the global locales array. For each supported locale, look for a matching translation. If one exists, link to /{language}/{path}/{slug.current}. If it doesn't, decide on a consistent behavior: hide the option, disable it with a label, or link to that locale's section index. Linking to a URL you know returns 404 is the one wrong answer.

Field-level content is simpler because all languages share a document, but you still need the slug for each language if slugs are localized. Project them as an array of {language, slug} so the switcher logic stays the same for both strategies.

Two smaller details matter. Mark each link with an hreflang attribute and the language name in its own language (Deutsch, not German). And when the switcher changes language, set the locale cookie that Proxy reads, so the user's explicit choice outranks Accept-Language on the next visit.

The switcher and hreflang share one data source

The _translations projection that drives the language switcher is the same data generateMetadata needs for alternates.languages. Load it once per page and use it for both. If the switcher and hreflang tags come from different logic, they eventually disagree, and search engines will index the version your users can't reach.

How do you preview each locale with Visual Editing before publishing?

Editors preview each locale by opening the localized frontend route inside the Studio. The Presentation Tool loads that route and resolves it to the right language document. The Presentation Tool is a Studio plugin that renders your Next.js app in an iframe with click-to-edit, configured through presentationTool({ previewUrl: { initial, previewMode: { enable: '/api/draft-mode/enable' } }, resolve: { mainDocuments, locations } }).

The locale-aware part is in mainDocuments. When the preview iframe navigates, the Presentation Tool matches the URL against route patterns defined with defineDocuments. Named parameters such as :slug are extracted and passed to the filter as GROQ variables, and the first matching pattern wins. Following that documented behavior, a pattern like '/:lang/posts/:slug' with the filter _type == "post" && slug.current == $slug && language == $lang should open the French document when an editor browses to a French URL. The Sanity docs don't show this exact locale example, so test it against your own routes. Order patterns from most specific to least specific so a catch-all doesn't win first.

A few requirements apply. Configuring allowOrigins needs sanity v3.85.0 or later, CORS must allow the Studio origin, and the draft mode route must accept the lang segment so previews land on /fr/... rather than the default locale. Storyblok and Contentful also offer per-language preview, so a preview feature alone doesn't set Sanity apart. The advantage here is that preview routing reuses the same URL params and GROQ filters as production routing.

Translation work can be automated too. The Agent API's client.agent.action.translate({schemaId, documentId, fromLanguage, toLanguage, targetDocument: {operation: 'create'}}) creates a translated draft. It's experimental, requires @sanity/client v7.1.0 or later, and needs a deployed schema (npx sanity@latest schemas deploy). Teams that use a translation vendor can send documents out through GROQ-powered webhooks or use the Transifex and Smartling plugins. Either way, the result is a language document that the routes above already know how to serve.

Locale routing with Next.js: how Sanity, Contentful, Storyblok, and Strapi compare

FeatureSanityContentfulStoryblokStrapi
Localization strategyChoose field-level (internationalized-array) or document-level (@sanity/document-internationalization) for each schema type, with both strategies in one project and one Content Lake.Locales are built into the platform and localization is enabled per field, so field-level is the native pattern. A one-entry-per-language setup has to be modeled by hand.Supports field-level translation, plus folder-level translation where each language gets its own content tree. The strategy is usually chosen when the space is set up.i18n is part of the Strapi v5 core, with a separate entry per locale. That maps naturally to document-style localization and per-locale slugs, and Strapi is open source and self-hosted.
Fallback to a default languageFallback order lives in the query: coalesce(title[language == $language][0].value, title[language == $baseLanguage][0].value) resolves it in one GROQ round trip.Fallback locales are configured in the Contentful web app and applied when content is delivered, so the fallback chain is set in the platform rather than in the query.Untranslated fields can return default-language values depending on the space and translation setup. Frontend code still decides how to handle pages that are missing entirely.Requests pass a locale parameter over REST or GraphQL. Falling back to a default locale is typically handled in frontend code or a custom controller.
Language switcher dataThe translation.metadata document links siblings. A references(^._id) subquery returns each translation's own slug and language alongside the page.With field-level localization, the switcher reads each locale's slug from the same entry. Separate-entry-per-language setups need custom reference fields to link translations.Field-level setups can store translated slugs per language. Folder-level trees need translations mapped to each other, either in the API response or in frontend code.Locale entries for the same content are linked, so the API can expose an entry's available localizations for building switcher links in the frontend.
Per-locale previewIn the Presentation Tool, defineDocuments route params such as :lang and :slug pass into GROQ filters, so preview resolves the matching language document inside the Studio.Live Preview shows draft content in the frontend through Contentful's preview SDK, and the frontend route chooses which locale is rendered.The Visual Editor is a strong built-in option for previewing pages per language, and it's a core part of Storyblok's editing experience.Preview can open frontend URLs for a content type. Per-locale preview depends on how the frontend reads the locale parameter that Strapi passes.
Translation workflow automationThe Agent API's translate action creates translated drafts (experimental). GROQ-powered webhooks and the Transifex and Smartling plugins connect to translation vendors.Translation vendor integrations are available through Contentful's app framework and marketplace, and they run inside its fixed editing interface.Translation vendors connect through Storyblok apps and integrations, with export and import workflows for sending content out to translators.Translation workflows are built with plugins or custom code, which gives full control on a self-hosted install but leaves more of the work to your team.

Ready to try Sanity?

See how Sanity can transform your enterprise content operations.