CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-astro

Astro is a modern site builder with web best practices, performance, and DX front-of-mind.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

i18n.mddocs/

Internationalization (i18n)

Astro provides comprehensive internationalization support with automatic locale routing, URL generation functions, and middleware for manual routing configurations.

Capabilities

Get Relative Locale URL

Generates a relative URL for a specific locale.

/**
 * Gets relative URL for a locale
 */
function getRelativeLocaleUrl(
  locale: string,
  path?: string,
  options?: GetLocaleOptions
): string;

interface GetLocaleOptions {
  prependWith?: string;
  normalizeLocale?: boolean;
}
import { getRelativeLocaleUrl } from 'astro:i18n';

const frenchUrl = getRelativeLocaleUrl('fr', '/about');
// Returns: "/fr/about"

const defaultUrl = getRelativeLocaleUrl('en', '/contact');
// Returns: "/contact" (if 'en' is default locale)

Get Absolute Locale URL

Generates an absolute URL for a specific locale.

/**
 * Gets absolute URL for a locale
 */
function getAbsoluteLocaleUrl(
  locale: string,
  path?: string,
  options?: GetLocaleOptions
): string;
import { getAbsoluteLocaleUrl } from 'astro:i18n';

const frenchUrl = getAbsoluteLocaleUrl('fr', '/about');
// Returns: "https://example.com/fr/about"

Get Relative Locale URL List

Gets all relative locale URLs for a path.

/**
 * Gets all relative locale URLs for a path
 */
function getRelativeLocaleUrlList(
  path?: string,
  options?: GetLocaleOptions
): string[];
import { getRelativeLocaleUrlList } from 'astro:i18n';

const urls = getRelativeLocaleUrlList('/about');
// Returns: ["/about", "/fr/about", "/es/about"]

Get Absolute Locale URL List

Gets all absolute locale URLs for a path.

/**
 * Gets all absolute locale URLs for a path
 */
function getAbsoluteLocaleUrlList(
  path?: string,
  options?: GetLocaleOptions
): string[];

Get Path By Locale

Gets the path segment for a locale code.

/**
 * Gets path segment for a locale code
 */
function getPathByLocale(locale: string): string;
import { getPathByLocale } from 'astro:i18n';

const path = getPathByLocale('fr');
// Returns: "fr"

const customPath = getPathByLocale('pt-BR');
// Returns: "pt-br" (normalized)

Get Locale By Path

Gets the locale code for a path segment.

/**
 * Gets locale code for a path segment
 */
function getLocaleByPath(path: string): string;

Path Has Locale

Checks if a path contains a locale segment.

/**
 * Checks if path contains a locale segment
 */
function pathHasLocale(path: string): boolean;
import { pathHasLocale } from 'astro:i18n';

console.log(pathHasLocale('/fr/about')); // true
console.log(pathHasLocale('/about')); // false

Manual Routing Functions

These functions are only available when using manual routing mode (routing: { strategy: 'manual' }).

Redirect To Default Locale

Redirects to the default locale if no locale is in the path.

/**
 * Redirects to default locale (manual routing only)
 */
function redirectToDefaultLocale(
  context: APIContext,
  statusCode?: ValidRedirectStatus
): Response | undefined;

type ValidRedirectStatus = 301 | 302 | 303 | 307 | 308;
// src/middleware.ts
import { defineMiddleware, redirectToDefaultLocale } from 'astro:middleware';

export const onRequest = defineMiddleware((context, next) => {
  const response = redirectToDefaultLocale(context, 302);
  if (response) return response;
  return next();
});

Not Found

Returns a 404 response for paths without a locale.

/**
 * Returns 404 for paths without locale (manual routing only)
 */
function notFound(
  context: APIContext,
  response?: Response
): Response | undefined;

Request Has Locale

Checks if the request has a locale in its path.

/**
 * Checks if request has locale (manual routing only)
 */
function requestHasLocale(context: APIContext): boolean;

Redirect To Fallback

Uses the built-in fallback system for missing translations.

/**
 * Uses fallback system for missing translations (manual routing only)
 */
function redirectToFallback(
  context: APIContext,
  response: Response
): Promise<Response>;

i18n Middleware

Creates i18n middleware for manual routing.

/**
 * Creates i18n middleware (manual routing only)
 */
function middleware(customOptions: RoutingConfig): MiddlewareHandler;

interface RoutingConfig {
  prefixDefaultLocale?: boolean;
  redirectToDefaultLocale?: boolean;
  fallbackType?: 'redirect' | 'rewrite';
}

Utility Functions

Normalize The Locale

Normalizes locale codes to standard format.

/**
 * Normalizes locale code (e.g., en_US -> en-US)
 */
function normalizeTheLocale(locale: string): string;
import { normalizeTheLocale } from 'astro:i18n';

console.log(normalizeTheLocale('en_US')); // "en-US"
console.log(normalizeTheLocale('pt_BR')); // "pt-BR"

Normalize The Path

Normalizes a path by removing trailing slashes.

/**
 * Normalizes a path by removing trailing slashes
 */
function normalizeThePath(path: string): string;

Get All Codes

Extracts all locale codes from a locale configuration.

/**
 * Extracts all locale codes including nested codes
 */
function getAllCodes(locales: Locales): string[];

To Codes

Extracts locale codes from locale configuration.

/**
 * Extracts locale codes from locale configuration
 */
function toCodes(locales: Locales): string[];

type Locales = string[] | LocaleConfig[];

interface LocaleConfig {
  path: string;
  codes: string[];
}

To Paths

Extracts locale paths from locale configuration.

/**
 * Extracts locale paths from locale configuration
 */
function toPaths(locales: Locales): string[];

Configuration

i18n is configured in astro.config.mjs:

import { defineConfig } from 'astro/config';

export default defineConfig({
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'fr', 'es'],
    routing: {
      prefixDefaultLocale: false,
      redirectToDefaultLocale: true,
      strategy: 'pathname-prefix-other-locales',
    },
    fallback: {
      fr: 'en',
      es: 'en',
    },
  },
});

Advanced Locale Configuration

export default defineConfig({
  i18n: {
    defaultLocale: 'en',
    locales: [
      'en',
      {
        path: 'fr',
        codes: ['fr', 'fr-FR', 'fr-CA'],
      },
      {
        path: 'es',
        codes: ['es', 'es-ES', 'es-MX'],
      },
    ],
  },
});

Domain-based Routing

export default defineConfig({
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'fr', 'es'],
    routing: {
      strategy: 'domains',
    },
    domains: {
      fr: 'https://example.fr',
      es: 'https://example.es',
    },
  },
});

Usage Patterns

Language Switcher

---
import { getRelativeLocaleUrlList } from 'astro:i18n';

const locales = ['en', 'fr', 'es'];
const currentPath = Astro.url.pathname;
const urls = getRelativeLocaleUrlList(currentPath);
---

<nav>
  {locales.map((locale, index) => (
    <a href={urls[index]}>
      {locale.toUpperCase()}
    </a>
  ))}
</nav>

Alternate Links

---
import { getAbsoluteLocaleUrlList } from 'astro:i18n';

const alternateUrls = getAbsoluteLocaleUrlList(Astro.url.pathname);
const locales = ['en', 'fr', 'es'];
---

<head>
  {alternateUrls.map((url, i) => (
    <link rel="alternate" hreflang={locales[i]} href={url} />
  ))}
</head>

Manual Routing Middleware

// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import {
  redirectToDefaultLocale,
  notFound,
  requestHasLocale,
} from 'astro:i18n';

export const onRequest = defineMiddleware((context, next) => {
  if (!requestHasLocale(context)) {
    const response = redirectToDefaultLocale(context);
    if (response) return response;

    return notFound(context);
  }

  return next();
});

Dynamic Locale Routing

---
// src/pages/[locale]/index.astro
export function getStaticPaths() {
  return [
    { params: { locale: 'en' } },
    { params: { locale: 'fr' } },
    { params: { locale: 'es' } },
  ];
}

const { locale } = Astro.params;
const translations = await import(`../../i18n/${locale}.json`);
---

<h1>{translations.title}</h1>

Common Issues

  • Default locale prefix: By default, the default locale is not prefixed in URLs. Set prefixDefaultLocale: true to change this.
  • Manual routing: When using strategy: 'manual', you must implement locale detection and routing yourself using the provided functions.
  • Fallback locales: Fallbacks only apply when content is missing, not for routing. Use domain routing for language-specific domains.

docs

assets.md

cli-and-build.md

configuration.md

container.md

content-collections.md

content-loaders.md

dev-toolbar.md

environment.md

i18n.md

index.md

integrations.md

middleware.md

server-actions.md

ssr-and-app.md

transitions.md

tile.json