Paraglide JS 提供了多种策略来确定用户的语言区域。
[!TIP]有关服务端集成的细节和框架示例,请参阅中间件指南。
策略通过 strategy 选项定义。策略按顺序求值——第一个成功返回语言区域的策略会被采用,后续策略不再检查。可以把这个数组看作一条简单的回退链:依次尝试各个策略,直到某个策略成功为止,这样 API 的行为始终可预测。
在下面的示例中,首先由 cookie 策略确定语言区域。如果没有找到 cookie (返回 undefined) ,则回退到 baseLocale。
[!NOTE]将以下内容添加到编译器配置中。具体写法因编译方式 (打包工具插件、CLI 或编程方式) 而略有不同。相关设置请参阅编译消息。
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
+ strategy: ["cookie", "baseLocale"]
})
策略顺序很重要:该数组是一个依次回退的列表,因此靠前的策略优先级更高。总能解析出语言区域的策略 (例如带通配符的 url 或 baseLocale) 通常应放在最后作为兜底,因为一旦命中,后续策略就不会再被执行。例如,如果将 preferredLanguage 放在 localStorage 之前,浏览器语言就总会优先生效,用户在 localStorage 中手动选择的语言则永远不会生效。
常见策略模式
以下是一些常见的策略模式及其适用场景:
以 URL 作为事实来源 (默认行为)
strategy: ["url", "baseLocale"];
如果语言区域应始终由 URL 决定,请使用此策略。URL 模式 (含通配符) 总能解析成功,因此 baseLocale 仅作为安全兜底。
优先采用用户偏好
strategy: ["localStorage", "cookie", "url", "baseLocale"];
如果希望回访用户无论从哪个 URL 进入,都能看到他们之前选择的语言,请使用此策略。只有在未存储偏好时,才由 URL 决定语言区域。
在 SSR 应用中,初始文档请求无法读取 localStorage。如果首次请求就必须遵循已存储的偏好,请同时加入服务器端可读取的策略,例如 cookie。
自动检测语言,并持久保存用户的手动选择
strategy: ["localStorage", "preferredLanguage", "url", "baseLocale"];
如果你希望首次访问的用户看到浏览器语言的内容,同时又能让用户手动切换的语言通过 localStorage 持久保存,就使用这种方式。
回退链从左到右依次为:localStorage → preferredLanguage → url → baseLocale。
由于 localStorage 排在最前,已保存的选择会覆盖浏览器设置。如果没有保存的值,则依次回退到 preferredLanguage、url,最后是 baseLocale。
[!NOTE]在同时对 URL 进行本地化的 SSR 应用中,初始文档请求阶段无法访问
localStorage。服务器会回退到preferredLanguage或url,可能因此重定向到与客户端水合后不一致的语言区域。如果持久保存的选择也需要在首次请求时生效,请添加一个服务器端可见的策略,例如cookie:strategy: ["localStorage", "cookie", "preferredLanguage", "url", "baseLocale"];
内置策略
cookie
cookie 策略会从 cookie 中读取语言区域。
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
+ strategy: ["cookie"]
})
baseLocale
返回设置中定义的 baseLocale。
当其他策略都未返回语言区域时 (例如 cookie 尚未设置) ,可以将它用作回退策略。
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
+ strategy: ["cookie", "baseLocale"]
})
globalVariable
通过全局变量确定语言区域。
此策略仅适用于测试环境或快速上手。在服务端环境中,设置全局变量可能引发跨请求问题;在客户端环境中,页面重新加载后语言区域不会保留。
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
+ strategy: ["globalVariable"]
})
preferredLanguage
根据浏览器设置或 HTTP 请求头自动检测用户的首选语言。
- 客户端:使用 navigator.languages
- 服务端:使用 Accept-Language 请求头
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
+ strategy: ["preferredLanguage", "baseLocale"]
})
该策略会按用户的偏好顺序匹配语言区域:
- 首先尝试精确匹配 (例如,若应用支持 "en-US",则直接使用)
- 否则回退到基础语言代码 (例如 "en")
例如:
- 如果用户偏好
fr-FR,fr;q=0.9,en;q=0.7,而你的应用支持["en", "fr"],则会使用fr - 如果用户偏好
en-US,而你的应用只支持["en", "de"],则会使用en
localStorage
从用户的 localStorage 中读取语言区域。
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
+ strategy: ["localStorage"]
})
此策略仅在浏览器中生效。在服务端会跳过 localStorage,改用下一个策略。在 SSR 应用中,如果希望初始请求就能使用已持久化的语言区域,请将它与服务端可读取的策略 (例如 cookie) 搭配使用。
url
根据 urlPatterns 配置,从 URL (路径名、域名等) 中确定语言区域。
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
+ strategy: ["url", "cookie"],
+ // url 策略使用这些模式(未指定则使用默认模式)
+ urlPatterns: [/* 你的模式 */]
})
基于 URL 的策略使用 Web 标准 URLPattern,根据你的 urlPatterns 配置来匹配和本地化 URL。
阅读 i18n 路由指南 →,全面了解语言区域前缀、路径名翻译、基于域名的路由以及 URL 模式配置。
[!NOTE]默认 URL 模式:如果没有指定
urlPatterns,Paraglide 会使用一个带通配符/:path(.*)?的默认模式,可匹配任意路径。没有语言区域前缀的路径会解析为你的基础语言区域。因此,url策略默认总能找到匹配项。
路由级策略覆盖
你可以通过 routeStrategies 按路由覆盖策略行为。
常见场景:
- 公开页面使用 URL 前缀 (
/de/...) ,并在全局策略中保留url。 /dashboard等私有路由始终不加前缀,应从 cookie 读取语言区域。- API/RPC 路由应完全跳过 i18n 中间件的处理。
如果不设置路由级覆盖,使用通配符模式的 url 会先将无前缀的路由解析为 baseLocale,而不会回退到 cookie。
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
strategy: ["url", "cookie", "baseLocale"],
routeStrategies: [
{ match: "/dashboard/:path(.*)?", strategy: ["cookie", "baseLocale"] },
{ match: "/rpc/:path(.*)?", strategy: ["cookie", "baseLocale"] },
{ match: "/api/:path(.*)?", exclude: true },
],
});
规则:
- 路由规则按声明顺序依次检查。
- 第一条匹配的规则生效。
exclude: true会为匹配的路由禁用 i18n 中间件行为。
编写自定义策略
编写基于 cookie、HTTP 请求头或 i18n 路由的自定义语言区域策略,将 Paraglide 集成到任意框架或应用中。
Paraglide JS 提供了两个覆盖 API,方便你按需调整:
overwriteGetLocale定义getLocale()函数,消息通过它确定语言区域overwriteSetLocale替换setLocale()函数,应用通过它切换语言区域
客户端和服务端各有独立的 Paraglide 运行时,因此需要在两端分别定义这些行为。
使用 overwriteGetLocale() 从 cookie、HTTP 请求头或 i18n 路由中读取语言区域。在客户端,尽量保留 setLocale() 的默认行为:它会先更新已配置的策略,再执行完整的文档导航或页面重新加载。
如果需要通过 overwriteSetLocale() 将语言区域持久化到已配置策略之外,请在持久化完成后,以完整的文档导航来完成客户端的语言区域切换。不要借助覆盖把普通的 URL 路由或 SSR 语言区域切换改成响应式的应用重新渲染;文档导航能让文档级状态、服务端渲染和客户端状态保持同步。
内置的 setLocale(locale, { reload: false }) 选项是一个刻意限定范围的逃生舱,仅适用于完全由客户端渲染、当前策略不包含 url 且自行管理完整响应式外壳的界面。不要以此为由,用覆盖重新实现响应式语言区域切换;参见 Basics 中的警告。
阅读架构文档,进一步了解 Paraglide 的内部工作原理。
动态解析语言区域 (cookie、HTTP 请求头、i18n 路由等)
如需动态解析语言区域,请向 getLocale() 传入一个返回语言区域的函数。借助它,你可以从 documentElement.lang 属性、cookie、语言区域路由或其他任意来源获取语言区域。
import { m } from "./paraglide/messages.js";
import { overwriteGetLocale } from "./paraglide/runtime.js";
overwriteGetLocale(() => document.documentElement.lang /** en */);
m.orange_dog_wheel(); // 你好,世界!
在服务器端,你可以通过 cookie、语言区域路由、HTTP 请求头或其他任何方式来确定语言区域。在服务器端调用 overwriteGetLocale() 时,要注意多个使用不同语言区域的请求同时到达时可能引发的竞态条件。
为避免这种情况,请在 Node 中使用 AsyncLocaleStorage,在其他服务端 JS 运行时中则使用对应的等效方案。
import { m } from "./paraglide/messages.js";
import { overwriteGetLocale, baseLocale } from "./paraglide/runtime.js";
import { AsyncLocalStorage } from "node:async_hooks";
const localeStorage = new AsyncLocalStorage();
overwriteGetLocale(() => {
//在 async local storage 上下文中,所有 getLocale() 调用都会返回已存储的语言区域
return localeStorage.getStore() ?? baseLocale;
});
export function onRequest(request, next) {
const locale = detectLocale(request); //从 headers、cookies 等来源解析语言区域
// 将当前请求的 async locale storage 设为
// 检测到的语言区域,然后让请求在该上下文中
// 继续执行
return localeStorage.run(locale, async () => await next());
}
自定义策略
除了覆盖 getLocale() 和 setLocale() 函数之外,Paraglide 还支持定义自定义策略,并将其与内置策略一起放入策略数组中。这样可以更简洁地封装自定义的语言区域解析逻辑。
自定义策略必须遵循 custom-<name> 的命名格式,其中 <name> 可以包含任意字符 (包括连字符、下划线等) 。
自定义策略既可以在客户端定义,也可以在服务端定义。你可以借此编写可复用的语言区域解析逻辑,并与 Paraglide 的运行时无缝集成。使用 defineCustomClientStrategy() 和 defineCustomServerStrategy() 函数分别为两种环境编写策略。参考下面的示例,定义你自己的自定义策略。
要使用自定义策略,需要在配置项目时将其加入 strategy 数组。
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
+ strategy: ["custom-userPreferences", "cookie", "baseLocale"]
})
客户端自定义策略
使用 defineCustomClientStrategy() 定义自定义策略,用于在客户端解析语言区域。处理器必须同时实现 getLocale() 和 setLocale() 方法。
适用场景:如果需要从仅在浏览器中可用的来源 (如查询参数、sessionStorage、URL 哈希等) 读写语言区域,请使用客户端自定义策略。
调用位置:在应用的初始化代码中定义自定义策略,且须在运行时开始使用这些策略之前完成。对于基于框架的应用,通常放在主应用文件、布局组件或插件/中间件配置中。
import { defineCustomClientStrategy } from "./paraglide/runtime.js";
// 示例 1:sessionStorage 策略
defineCustomClientStrategy("custom-sessionStorage", {
getLocale: () => {
return sessionStorage.getItem("user-locale") ?? undefined;
},
setLocale: (locale) => {
sessionStorage.setItem("user-locale", locale);
},
});
// 示例 2:查询参数策略(正好解决了最初的问题!)
defineCustomClientStrategy("custom-queryParam", {
getLocale: () => {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get("locale") ?? undefined;
},
setLocale: (locale) => {
const url = new URL(window.location);
url.searchParams.set("locale", locale);
window.history.replaceState({}, "", url.toString());
},
});
// 示例 3:URL 哈希策略
defineCustomClientStrategy("custom-hash", {
getLocale: () => {
const hash = window.location.hash.slice(1); // 去掉 #
return hash.startsWith("lang=") ? hash.replace("lang=", "") : undefined;
},
setLocale: (locale) => {
window.location.hash = `lang=${locale}`;
},
});
服务端自定义策略
服务端自定义策略请使用 defineCustomServerStrategy() 定义。处理器只需实现 getLocale() 方法,该方法接受一个可选的 Request 参数。
使用场景:需要从服务端特有的来源 (如自定义请求头、数据库、身份验证系统等) 读取语言区域时,请使用服务端自定义策略。
调用位置:在服务器初始化代码中定义自定义策略,并确保在中间件开始处理请求之前完成。对于使用框架的应用,通常放在服务器配置文件或中间件配置中。
异步支持:服务端自定义策略支持异步操作!如果 getLocale 方法返回 Promise,系统会自动改用异步方式提取语言区域。
import { defineCustomServerStrategy } from "./paraglide/runtime.js";
// 示例 1:自定义请求头策略
defineCustomServerStrategy("custom-header", {
getLocale: (request) => {
const locale = request?.headers.get("X-Custom-Locale");
return locale ?? undefined;
},
});
// 示例 2:异步数据库策略
defineCustomServerStrategy("custom-database", {
getLocale: async (request) => {
const userId = extractUserIdFromRequest(request);
if (!userId) return undefined;
try {
// 这里支持异步调用!
return await getUserLocaleFromDatabase(userId);
} catch (error) {
console.warn("Failed to fetch user locale:", error);
return undefined;
}
},
});
// 示例 3:服务端读取查询参数(用于 SSR)
defineCustomServerStrategy("custom-serverQuery", {
getLocale: (request) => {
const url = new URL(request.url);
return url.searchParams.get("locale") ?? undefined;
},
});
进阶示例:全栈用户偏好策略
下面是一个完整示例,展示如何在客户端和服务端实现用户偏好策略,并支持异步访问数据库:
// 文件:src/locale-strategies.js
import {
defineCustomClientStrategy,
defineCustomServerStrategy,
} from "./paraglide/runtime.js";
import {
getUserLocale,
setUserLocale,
extractUserIdFromRequest,
} from "./services/userService.js";
// 客户端策略:在浏览器中处理用户偏好
defineCustomClientStrategy("custom-userPreference", {
getLocale: () => {
// 从内存缓存或框架状态存储中读取;返回 undefined 则回退
return window.__userLocale ?? undefined;
},
setLocale: async (locale) => {
try {
// 通过 API 更新数据库中的用户偏好
await setUserLocale(locale);
window.__userLocale = locale;
// 可选:同时更新 URL 查询参数,使更改立即生效
const url = new URL(window.location);
url.searchParams.set("locale", locale);
window.history.replaceState({}, "", url.toString());
} catch (error) {
console.warn("Failed to save user locale preference:", error);
// 即使保存失败,策略仍可成功执行
}
},
});
// 服务端策略:异步查询数据库
defineCustomServerStrategy("custom-userPreference", {
getLocale: async (request) => {
const userId = extractUserIdFromRequest(request);
if (!userId) return undefined;
try {
// 异步数据库调用:现已完全支持!
return await getUserLocale(userId);
} catch (error) {
console.warn("Failed to fetch user locale from database:", error);
return undefined; // 回退到下一个策略
}
},
});
自定义策略的优势
与传统的 overwriteGetLocale() 方式相比,自定义策略有以下几点优势:
- 可组合性:可以与内置策略放在同一个策略数组中组合使用
- 优先级处理:遵循策略顺序,可回退到其他策略
- 框架集成:更便于随框架适配器一起打包和分发
- 类型安全:为自定义策略处理器提供更好的 TypeScript 支持
- 错误隔离:某个自定义策略失败时,会继续执行下一个策略
- 异步支持:服务端策略可以执行数据库查询等异步操作
- 中间件兼容:与 Paraglide 的服务端中间件无缝配合
重要说明
异步支持:
- ✅ 服务端策略支持异步的
getLocale方法 - ❌ 客户端策略的
getLocale方法必须是同步的(但setLocale可以是异步的) - ✅ 只要有任一自定义策略使用了异步
setLocale,主setLocale()函数就会变为异步,页面重新加载时会等待所有异步操作完成 - 如果需要在客户端异步检测语言区域,请改用
overwriteGetLocale()方案
策略优先级:
- 自定义策略按其在
strategy数组中的顺序依次处理 - 如果某个自定义策略返回
undefined,系统会回退到下一个策略 - 所有策略(自定义和内置)都按你定义的顺序处理,服务端和客户端均是如此
- 如果自定义策略排在一个总能解析出结果的策略之后(例如使用默认 URL 模式的
url,或baseLocale),它永远不会执行。若要将其用作回退,请把它放在这些策略之前。参见本页顶部的“策略顺序很重要”
校验:
自定义策略名称必须以 custom- 开头,且后面至少还有一个字符。custom- 之后的名称部分可包含任意字符,包括连字符、下划线等。
有效示例:
custom-sessionStoragecustom-user-preferencecustom-query_paramcustom-database
无效示例:
custom-(前缀后没有名称)my-custom-strategy(不是以custom-开头)sessionStorage(缺少custom-前缀)
