- Docs
- Named and translated routes
Named and translated routes
Use routeNames, active child links and shared translated destinations for navigation, language switching and SEO.
The starter includes a typed named-route catalog and a shared destination resolver.
Use it for navigation, language switching and SEO. Astro still owns route files,
getStaticPaths and URL formatting; declaring a name does not create a page.
Named static routes
The project convention is one routes.ts beside each locale’s dictionary
index. This is the editable inventory of public page names and their real,
locale-free URLs. Keep route data outside UI dictionary domains: it must not be
translated as copy or bundled in a client translation payload.
| File | Owns |
|---|---|
src/config/routes.ts | Stable routeNames, shared types and the derived cross-language view. |
src/i18n/dictionaries/<locale>/routes.ts | That language’s page names and actual paths; null means unavailable. |
src/i18n/route-tables.ts | Locale-to-table imports only; no duplicate URLs. |
src/i18n/routes.ts | Shared resolution and inventory helpers used by consumers. |
A minimal project includes home.index; selecting Welcome also includes
demo.index. To add a real about page, extend only the routeNames declaration
in src/config/routes.ts, preserving its imports, types and derived routes:
export const routeNames = {
home: 'home.index',
about: 'company.about'
} as const
Preserve any other names already present, including the optional demo. Declare the same keys in each configured locale’s table. For a minimal two-language site:
// src/i18n/dictionaries/en-us/routes.ts
import type { RouteTable } from '../../../config/routes'
export default {
'home.index': '/',
'company.about': '/about'
} satisfies RouteTable
// src/i18n/dictionaries/es-mx/routes.ts
import type { RouteTable } from '../../../config/routes'
export default {
'home.index': '/',
'company.about': '/nosotros'
} satisfies RouteTable
RouteTable requires every declared name and rejects unknown names. Use null
when that page has no translation, including unfinished languages. Do not copy
the default language’s URL as a placeholder. Each table is a static default object
with literal route-name keys and string/null values; installer operations inspect
syntax without executing these modules. Keep path builders and CMS queries outside
these files. The same path in two languages is written explicitly in both tables.
The installer emits only selected languages and registers their tables. Later
locale add reads the current default table’s keys, creates a new routes.ts with
all values set to null, and registers it without touching existing URLs. It leaves
the language inactive. Fill dictionary copy, language labels and actual route paths,
then verify pages before activation. Older copied projects without this structure
are preserved; locale add is not a source migration command. New Welcome additions
require this route-table contract and report a no-write conflict if it is missing;
merge the documented source changes before retrying.
Names and paths are structural data; visible labels stay in UI dictionaries. Changing a path here does not move an Astro page, create a redirect or rename a CMS record. Update the owning route generation and any intentional redirects too. Do not duplicate absolute URLs or locale prefixes here: Astro’s helpers add the configured site/base, default-language policy and trailing-slash behavior.
Inside a section, link to a known page by its name:
---
import Link from '@/components/Link/index.astro'
import { routeNames } from '@/config/routes'
import { getDictionary } from '@/i18n'
const dictionary = getDictionary(Astro.currentLocale)
---
<Link routeName={routeNames.home} variant='nav' currentMatch='descendants'>
{dictionary.site.name}
</Link>
Use the same identity in the page’s layout: <Main routeName={routeNames.about}>.
Main forwards it to SEO and its default DemoHeader, whose LanguagePicker receives
the same context. A custom header should receive the page identity explicitly and
pass it to <LanguagePicker {...pageRoute} />. For custom navigation URL data,
use routePath({ routeName: routeNames.about }, locale) from @/i18n/routes, then
format it with getRelativeLocaleUrl. A missing current-locale path throws rather
than linking to an invented destination; omit unavailable navigation items using
resolveRoutePaths({ routeName: routeNames.about })[locale] first.
Link and Button accept either href or routeName. Main, SEO and
LanguagePicker accept exactly one of path, routeName or localizedPaths.
Existing href and shared path usages continue to work. Named links use the
current locale and Astro’s configured base/prefix rules without browser JavaScript.
currentMatch='exact' marks the destination page; 'descendants' also marks
segment-bounded child paths as a current location. Home remains exact-only.
See Link for explicit overrides and client lifecycle.
The route file must generate the paths declared in the catalog. For the about
example above, create src/pages/[...route].astro and a real About section with
its translated copy before using this complete page composition:
---
import Main from '@/layouts/Main.astro'
import About from '@/sections/About/index.astro'
import { routeNames } from '@/config/routes'
import { resolveRoutePaths } from '@/i18n/routes'
import { defaultLocale } from '@/i18n/config'
export const getStaticPaths = () =>
Object.entries(resolveRoutePaths({ routeName: routeNames.about })).map(
([locale, path]) => ({
params: {
route:
[locale === defaultLocale ? '' : locale, path.slice(1)]
.filter(Boolean)
.join('/') || undefined
}
})
)
---
<Main routeName={routeNames.about}>
<About />
</Main>
This example follows the starter’s default unprefixed language configuration. Use route parameters matching your own file structure. A real page’s route must have one owner; avoid another route producing the same URLs. The catalog does not replace Astro’s route priority rules or parameter generation. Do not reverse-match the current URL or inspect route-builder function source to guess page identity. Active matching controls navigation, not route generation.
Navigation inventories and sitemaps
routeEntries(locale) from @/i18n/routes returns { routeName, path } entries
for that active locale, omitting null/absent translations. Use it to inspect the
public static-page inventory or compose an HTML sitemap. For a curated header or
footer, keep a small list of route names and translated labels in the owner;
look up destinations from the tables instead of maintaining another URL list.
The demo follows this pattern. Do not automatically display every catalog entry
in primary navigation or use route names as visitor-facing labels.
Inside a section, real URLs can be inspected with the native helper:
import { getRelativeLocaleUrl, getAbsoluteLocaleUrl } from 'astro:i18n'
import { routeEntries } from '@/i18n/routes'
import { resolveLocale } from '@/i18n'
const locale = resolveLocale(Astro.currentLocale)
const pages = routeEntries(locale).map(({ routeName, path }) => ({
routeName,
href: getRelativeLocaleUrl(locale, path),
url: getAbsoluteLocaleUrl(locale, path)
}))
For an HTML sitemap, render those destinations using translated labels and Link
with localize={false}. Apply the site’s public/indexability policy separately.
A route’s presence is not an authorization rule or proof it should be indexed.
Keep endpoints, status pages and private operation URLs out of this public page
inventory; auth and noindex remain with their existing owners.
The installed XML sitemap integration discovers generated pages. It does not
create pages from these tables or automatically group different translated paths
by route name. For such alternates, use the same name-to-destination mapping in
its documented serialize configuration and include only generated or explicitly
verified public destinations. Preserve noindex filtering. Do not blindly turn the
whole catalog into customPages: that can publish unbuilt/private URLs. Dynamic
records require their provider’s actual translation groups and discovery policy,
not placeholder paths or a new build-time crawl of the whole API.
See Astro sitemap configuration.
Dynamic translated records
For API/CMS records, normalize their actual translation relation to
LocalizedPaths, then pass <Main localizedPaths={paths}>. This sets canonical,
self/cross-language alternates and the default header’s language destinations from
the same map. A standalone picker uses <LanguagePicker localizedPaths={paths} />.
Inactive and absent translations are omitted; the picker renders only when at
least two destinations are available. SEO throws if the current page has no path.
alternateLocales may further restrict SEO destinations; x-default requires an
available, permitted default-language destination.
The resolver validates locale-free site paths and uses only active locales. It performs no fetch, publication/access validation or automatic slug translation. The content boundary must provide only real, published, accessible equivalents. Neither a route name nor a common parent path identifies a dynamic record’s translations. Do not append the old slug to another language’s section URL.
Inspect the source contract first
API and CMS records
When asked to consume an API, determine:
- Which field identifies a translation group independently of language? Use the provider’s documented localization relation, shared content key or explicit mapping. Record IDs may differ between translations. Never infer relationships from matching titles, similar slugs, array order or assumed shared IDs.
- Which fields contain locale, slug or full route, publication state and access restrictions? Identify nested categories/parents and route segments too.
- Can a content query include its published translations? Prefer that query to downloading every record or issuing one request per language. Otherwise use a bounded lookup by the explicit translation relation.
- Are the consuming pages prerendered, rendered on demand, or browser-loaded? An API source alone does not imply SSR. Keep SSG unless requirements change it.
If there is no reliable relationship, document the missing API contract and ask for that information. Do not fabricate equivalent destinations. A project may add an explicit mapping when its provider lacks localization relations.
Normalize destinations once
At the content boundary, validate provider data and produce a small, typed
representation using the installed LocalizedPaths type:
import type { LocalizedPaths } from '@/i18n/routes'
type LocalizedContentRoutes = {
translationKey: string
paths: LocalizedPaths
}
Locale comes from the project’s i18n configuration. Each value is the complete
locale-free site path, including translated parent/category segments. For
example, one item might map en-us to /articles/hello and es-mx to
/articulos/hola. en-us is English and es-mx is Mexican Spanish. These example
paths are not routes shipped by the starter and do not activate another locale.
Only include configured active locales and published, accessible translations. Reject duplicate locale entries for the same group, conflicting group identities, invalid paths and ambiguous destinations. Validate API URLs before reducing them to site paths: do not turn an external host or unsafe scheme into a navigation link. For this same-site contract, reject protocol-relative paths, queries and fragments; handle genuine cross-domain localization through an explicit separate project policy. Encode raw slug segments exactly once when constructing paths.
Resolve once per page/data load, then share the result with navigation and SEO. Components continue to infer their own current locale. Passing a set of known content destinations is different from passing redundant locale props to every component. Avoid a separate API request in each component or a global mutable map shared across requests.
Resolve at the correct time
| Consumer | Resolution and freshness |
|---|---|
| Static pages and local collections | Resolve from route definitions/translation groups during the build. |
| SSG pages using an API or CMS | Fetch and validate the published snapshot at build time; generate paths and alternates from that same snapshot. Changes require a rebuild, optionally triggered by a CMS webhook. |
| SSR or another on-demand route | Query the requested item and its published translations during the request. Configure an adapter/on-demand route only when needed; this does not require converting the whole starter to SSR. |
| Live Collections | Resolve in the on-demand consumer using the current entry and its localization relationship. A live data source does not update previously generated static HTML. |
| Browser-loaded content | Update the selector when the current content response arrives. Ignore/cancel stale responses after content or locale navigation. Keep credentials server-side. |
For SSR, apply the API client’s existing timeout, validation and error policy. If caching, include the content identity, locale, publication/access scope and other relevant query dimensions in the key. Define a TTL or invalidation strategy; do not share private response data in a public cache. A provider translation can be deleted after resolution: no static snapshot or cache guarantees perpetual availability.
For indexable content, render canonical and hreflang metadata in initial SSG/SSR HTML. Browser-only updates to navigation do not substitute for that metadata. A Server Island cannot retroactively replace the parent page’s static head; resolve metadata with the page or choose an on-demand page when required.
Missing translations and request failures
Default to omitting a language option when its equivalent translation is absent, unpublished or inaccessible. A project can explicitly offer that language’s listing/home as a fallback, but label it as such and never advertise it as the article’s equivalent in hreflang. Never guess a translated route by replacing the locale prefix. Do not use HTTP probes for every generated language link.
Distinguish confirmed missing content from a provider error. Invalid/unavailable build data should fail the build according to the loader policy, not publish a silently empty translation snapshot. On demand, follow the page’s documented failure policy; omit unresolved alternates or return an appropriate error rather than construct guessed URLs. Return a real 404 when the requested content is confirmed missing. Keep all user-facing fallback/error copy in dictionaries.
Do not blindly carry pagination, filters, query strings or fragments into another translation. Preserve only values with an explicit equivalent in the destination. Changing language to an item with a different slug should still preserve its translation-group identity.
Navigation and SEO must agree
Use the same validated destinations for LanguagePicker, self/cross-language hreflang and sitemap alternates where applicable. Compute each page’s canonical from its own actual route; another language’s URL is an alternate, not its canonical. Include x-default only under a defined policy with a real destination. Do not treat a listing/home fallback as an equivalent translation.
Use Astro helpers to apply prefixes, base paths and trailing-slash configuration
to each destination’s own locale-free path. The default locale may have no URL
prefix. Do not concatenate prefixes manually or localize an already resolved URL
again through Link; use localize={false} for those links.
Verification when implementing this integration
Exercise the actual routes and rendered navigation/metadata:
- Same path across locales, different slugs, translated parent segments, and different record IDs linked to the same translation group.
- Default locale without a prefix, non-default locales and configured base paths.
- Missing/unpublished translations, duplicate locales, malformed paths, unsupported locales and provider failures.
- SSG destinations matching the paths generated from the same published snapshot; SSR destinations matching current public records and the cache policy.
- Navigation and hreflang agreement, correct self canonical, and no hreflang to a fallback listing or missing translation.
- Browser navigation races and allowed query/hash behavior when relevant.
Also test newly added informational/legal routes through the project’s locale route structure, and validate locale inputs for Action feedback. Pass the parent locale explicitly across isolated requests, including when building their links. Keep the technical root 404 entry discoverable by the selected adapter; verify its actual fallback language and status rather than moving it into a locale folder or making it on-demand for every deployment profile. A purely static deployment must retain a static-compatible error page.
Record the provider mapping, rendering mode, freshness policy, missing-translation
behavior and performed verification in the consuming project’s .agents memory.
Verify the real provider mapping and generated routes; the shared resolver cannot establish that upstream content exists.
Official references: Astro internationalization, URL helpers, routing.
Parent query context for Server Islands
A Server Island’s Astro.url describes its isolated endpoint, not the page that
contains it. Pass known route data and locale explicitly as props. On an SSG
page, visitor query parameters do not exist during frontmatter execution, so
passing Astro.url.search at build time cannot transport the visitor’s filters.
Astro documents reading the island request’s Referer for this case:
https://docs.astro.build/en/guides/server-islands/#accessing-the-page-url-in-a-server-island.
For a public listing, this frontmatter fragment resolves same-origin parent context and a bounded, allowlisted filter. It must run inside the island:
const resolveParent = (referer: string | null, site: URL) => {
if (!referer) return undefined
try {
const parent = new URL(referer)
return parent.origin === site.origin ? parent : undefined
} catch {
return undefined
}
}
const parent = resolveParent(Astro.request.headers.get('referer'), Astro.site!)
const name = parent?.searchParams.get('name')?.trim().slice(0, 100) ?? ''
// Query the real provider using only validated filters and the explicit locale.
// Referer-dependent HTML must not be shared under the island endpoint's URL.
Astro.response.headers.set('Cache-Control', 'private, no-store')
The production site’s configured origin must match the parent origin. A preview needs its own correct site configuration or a separately validated allowed origin; do not accept arbitrary request headers as trusted origins. Referer is optional and caller-controlled: it cannot authorize a user or resource. Validate filter enums, numeric ranges and provider arguments independently.
Define the missing-context policy in the consuming product. An unfiltered public listing is acceptable only when that is the agreed behavior; if an explicit filter is required, show translated recovery feedback instead. Do not silently return fixtures when a real provider fails. Referrer-Policy may remove the path/query, and production delivery must be tested with filters, reload, missing/malformed/foreign Referer and navigation between different queries.
Keep the returned island HTML private/no-store when it depends on Referer or
user context. A server-side data cache may separately use normalized locale and
all validated filter dimensions as its key. Vary: Referer alone is not a
portable substitute for an explicit CDN policy. If reliable context or shared
HTTP caching is required, use an explicit browser request carrying validated
filters to an owned endpoint, or a request-rendered page; define its cache key
and fallback there. Do not retrofit a second global query router into every
starter project.