Skip to content
454 changes: 183 additions & 271 deletions src/content/docs/en/guides/internationalization.mdx

Large diffs are not rendered by default.

276 changes: 276 additions & 0 deletions src/content/docs/en/reference/api-reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1395,6 +1395,282 @@ This function can be used by integrations/adapters to programmatically execute t

A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error.

## Internationalization (`astro:i18n`)

<p><Since v="3.5.0" /></p>

This module provides functions to help you create URLs using your project's configured locales.

Creating routes for your project with the i18n router will depend on certain configuration values you have set that affect your page routes. When creating routes with these functions, be sure to take into account your individual settings for:

- [`base`](/en/reference/configuration-reference/#base)
- [`trailingSlash`](/en/reference/configuration-reference/#trailingslash)
- [`build.format`](/en/reference/configuration-reference/#buildformat)
- [`site`](/en/reference/configuration-reference/#site)

Also, note that the returned URLs created by these functions for your `defaultLocale` will reflect your `i18n.routing` configuration.

For features and usage examples, [see our i18n routing guide](/en/guides/internationalization/).

### `getRelativeLocaleUrl()`

`getRelativeLocaleUrl(locale: string, path?: string, options?: GetLocaleOptions): string`

Use this function to retrieve a relative path for a locale. If the locale doesn't exist, Astro throws an error.

```astro
---
getRelativeLocaleUrl("fr");
// returns /fr

getRelativeLocaleUrl("fr", "");
// returns /fr

getRelativeLocaleUrl("fr", "getting-started");
// returns /fr/getting-started

getRelativeLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog"
});
// returns /blog/fr-ca/getting-started

getRelativeLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog",
normalizeLocale: false
});
// returns /blog/fr_CA/getting-started
---
```

### `getAbsoluteLocaleUrl()`

`getAbsoluteLocaleUrl(locale: string, path: string, options?: GetLocaleOptions): string`

Use this function to retrieve an absolute path for a locale when [`site`] has a value. If [`site`] isn't configured, the function returns a relative URL. If the locale doesn't exist, Astro throws an error.


```astro title="src/pages/index.astro"
---
// If `site` is set to be `https://example.com`

getAbsoluteLocaleUrl("fr");
// returns https://example.com/fr

getAbsoluteLocaleUrl("fr", "");
// returns https://example.com/fr

getAbsoluteLocaleUrl("fr", "getting-started");
// returns https://example.com/fr/getting-started

getAbsoluteLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog"
});
// returns https://example.com/blog/fr-ca/getting-started

getAbsoluteLocaleUrl("fr_CA", "getting-started", {
prependWith: "blog",
normalizeLocale: false
});
// returns https://example.com/blog/fr_CA/getting-started
---
```

### `getRelativeLocaleUrlList()`

`getRelativeLocaleUrlList(path?: string, options?: GetLocaleOptions): string[]`


Use this like [`getRelativeLocaleUrl`](#getrelativelocaleurl) to return a list of relative paths for all the locales.


### `getAbsoluteLocaleUrlList()`

`getAbsoluteLocaleUrlList(path?: string, options?: GetLocaleOptions): string[]`

Use this like [`getAbsoluteLocaleUrl`](/en/guides/internationalization/#custom-locale-paths) to return a list of absolute paths for all the locales.

### `getPathByLocale()`

`getPathByLocale(locale: string): string`

A function that returns the `path` associated to one or more `codes` when [custom locale paths](/en/guides/internationalization/#custom-locale-paths) are configured.

```js title="astro.config.mjs"
export default defineConfig({
i18n: {
locales: ["es", "en", {
path: "french",
codes: ["fr", "fr-BR", "fr-CA"]
}]
}
})
```

```astro title="src/pages/index.astro"
---
getPathByLocale("fr"); // returns "french"
getPathByLocale("fr-CA"); // returns "french"
---
```

### `getLocaleByPath`

`getLocaleByPath(path: string): string`

A function that returns the `code` associated to a locale `path`.

```js title="astro.config.mjs"
export default defineConfig({
i18n: {
locales: ["es", "en", {
path: "french",
codes: ["fr", "fr-BR", "fr-CA"]
}]
}
})
```

```astro title="src/pages/index.astro"
---
getLocaleByPath("french"); // returns "fr" because that's the first code configured
---
```

### `redirectToDefaultLocale()`

`redirectToDefaultLocale(context: APIContext, statusCode?: ValidRedirectStatus): Promise<Response>`

<p><Since v="4.6.0" /></p>

:::note
Available only when `i18n.routing` is set to `"manual"`
:::

A function that returns a `Response` that redirects to the `defaultLocale` configured. It accepts an optional valid redirect status code.

```js title="middleware.js"
import { defineMiddleware } from "astro:middleware";
import { redirectToDefaultLocale } from "astro:i18n";

export const onRequest = defineMiddleware((context, next) => {
if (context.url.pathname.startsWith("/about")) {
return next();
} else {
return redirectToDefaultLocale(context, 302);
}
})
```

### `redirectToFallback()`

`redirectToFallback(context: APIContext, response: Response): Promise<Response>`

<p><Since v="4.6.0" /></p>

:::note
Available only when `i18n.routing` is set to `"manual"`
:::

A function that allows you to use your [`i18n.fallback` configuration](/en/reference/configuration-reference/#i18nfallback) in your own middleware.

```js title="middleware.js"
import { defineMiddleware } from "astro:middleware";
import { redirectToFallback } from "astro:i18n";

export const onRequest = defineMiddleware(async (context, next) => {
const response = await next();
if (response.status >= 300) {
return redirectToFallback(context, response)
}
return response;
})
```

### `notFound()`

`notFound(context: APIContext, response: Response): Promise<Response>`

<p><Since v="4.6.0" /></p>

:::note
Available only when `i18n.routing` is set to `"manual"`
:::

Use this function in your routing middleware to return a 404 when:
- the current path isn't a root. e.g. `/` or `/<base>`
- the URL doesn't contain a locale

When a `Response` is passed, the new `Response` emitted by this function will contain the same headers of the original response.

```js title="middleware.js"
import { defineMiddleware } from "astro:middleware";
import { notFound } from "astro:i18n";

export const onRequest = defineMiddleware((context, next) => {
const pathNotFound = notFound(context);
if (pathNotFound) {
return pathNotFound;
}
return next();
})
```

### `middleware()`

`middleware(options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean })`

<p><Since v="4.6.0" /></p>

:::note
Available only when `i18n.routing` is set to `"manual"`
:::

A function that allows you to programmatically create the Astro i18n middleware.

This is use useful when you still want to use the default i18n logic, but add only a few exceptions to your website.

```js title="middleware.js"
import { middleware } from "astro:i18n";
import { sequence, defineMiddleware } from "astro:middleware";

const customLogic = defineMiddleware(async (context, next) => {
const response = await next();

// Custom logic after resolving the response.
// It's possible to catch the response coming from Astro i18n middleware.

return response;
});

export const onRequest = sequence(customLogic, middleware({
prefixDefaultLocale: true,
redirectToDefaultLocale: false
}))
```

### `requestHasLocale()`

`requestHasLocale(context: APIContext): boolean`

<p><Since v="4.6.0" /></p>

:::note
Available only when `i18n.routing` is set to `"manual"`
:::

Checks whether the current URL contains a configured locale. Internally, this function will use `APIContext#url.pathname`.

```js title="middleware.js"
import { defineMiddleware } from "astro:middleware";
import { requestHasLocale } from "astro:i18n";

export const onRequest = defineMiddleware(async (context, next) => {
if (requestHasLocale(context)) {
return next();
}
return new Response("Not found", { status: 404 });
})
```

## Built-in Components

Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/en/reference/configuration-reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1376,7 +1376,7 @@ export default defineConfig({
});
```

Both page routes built and URLs returned by the `astro:i18n` helper functions [`getAbsoluteLocaleUrl()`](/en/guides/internationalization/#getabsolutelocaleurl) and [`getAbsoluteLocaleUrlList()`](/en/guides/internationalization/#getabsolutelocaleurllist) will use the options set in `i18n.domains`.
Both page routes built and URLs returned by the `astro:i18n` helper functions [`getAbsoluteLocaleUrl()`](/en/reference/api-reference/#getabsolutelocaleurl) and [`getAbsoluteLocaleUrlList()`](/en/reference/api-reference/#getabsolutelocaleurllist) will use the options set in `i18n.domains`.

See the [Internationalization Guide](/en/guides/internationalization/#domains-experimental) for more details, including the limitations of this experimental feature.

Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/es/reference/configuration-reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1306,5 +1306,5 @@ export default defineConfig({
},
});
```
Ambas rutas de página construidas y URLs devueltas por las funciones auxiliares `astro:i18n` [`getAbsoluteLocaleUrl()`](/es/guides/internationalization/#getabsolutelocaleurl) y [`getAbsoluteLocaleUrlList()`](/es/guides/internationalization/#getabsolutelocaleurllist) utilizarán las opciones establecidas en `i18n.domains`.
Ambas rutas de página construidas y URLs devueltas por las funciones auxiliares `astro:i18n` `getAbsoluteLocaleUrl()` y `getAbsoluteLocaleUrlList()` utilizarán las opciones establecidas en `i18n.domains`.
Ver la [Guía de Internacionalización](/es/guides/internationalization/#domains-experimental) para más detalles, incluyendo las limitaciones de esta característica experimental.
2 changes: 1 addition & 1 deletion src/content/docs/ja/reference/configuration-reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1223,6 +1223,6 @@ export default defineConfig({
});
```

作成されたページルートと、`astro:i18n`のヘルパー関数[`getAbsoluteLocaleUrl()`](/ja/guides/internationalization/#getabsolutelocaleurl)および[`getAbsoluteLocaleUrlList()`](/ja/guides/internationalization/#getabsolutelocaleurllist)から返されたURLは、ともに`i18n.domains`に設定されたオプションを使用します。
作成されたページルートと、`astro:i18n`のヘルパー関数[`getAbsoluteLocaleUrl()`](/ja/reference/api-reference/#getabsolutelocaleurl)および[`getAbsoluteLocaleUrlList()`](/ja/reference/api-reference/#getabsolutelocaleurllist)から返されたURLは、ともに`i18n.domains`に設定されたオプションを使用します。

この実験的機能の制限を含む詳しい情報については、[国際化ガイド](/ja/guides/internationalization/#domains-experimental)を参照してください。
2 changes: 1 addition & 1 deletion src/content/docs/ko/guides/internationalization.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Astro의 i18n 라우팅을 사용하면 기본 언어 구성, 상대 페이지 U

### i18n 라우팅 구성

1. [기본 언어 (`defaultLocale`) 및 지원할 모든 언어 목록 (`locales`)](#defaultlocale-및-locales)을 사용하여 Astro 구성에 `i18n` 객체를 추가하여 라우팅 옵션을 활성화합니다.
1. [기본 언어 (`defaultLocale`) 및 지원할 모든 언어 목록 (`locales`)](/ko/reference/configuration-reference/#i18nlocales)을 사용하여 Astro 구성에 `i18n` 객체를 추가하여 라우팅 옵션을 활성화합니다.

```js title="astro.config.mjs"
import { defineConfig } from 'astro/config';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1338,6 +1338,6 @@ export default defineConfig({
});
```

`astro:i18n` 辅助函数 [`getAbsoluteLocaleUrl()`](/zh-cn/guides/internationalization/#getabsolutelocaleurl)[`getAbsoluteLocaleUrlList()`](/zh-cn/guides/internationalization/#getabsolutelocaleurllist) 构建的页面路由和 URL 将使用 `i18n.domains` 中设置的选项。
`astro:i18n` 辅助函数 `getAbsoluteLocaleUrl()` 和 `getAbsoluteLocaleUrlList()` 构建的页面路由和 URL 将使用 `i18n.domains` 中设置的选项。

查看 [国际化指南](/zh-cn/guides/internationalization/#domains-experimental) 以获取更多细节,包括这个实验性功能的限制。