Skip to content

Commit 9f20e0d

Browse files
authored
fix(web): sync docs locale cookie on alias redirects (anomalyco#13109)
1 parent ebb907d commit 9f20e0d

2 files changed

Lines changed: 29 additions & 7 deletions

File tree

packages/app/src/context/language.tsx

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ export type Locale =
5757
type RawDictionary = typeof en & typeof uiEn
5858
type Dictionary = i18n.Flatten<RawDictionary>
5959

60+
function cookie(locale: Locale) {
61+
return `oc_locale=${encodeURIComponent(locale)}; Path=/; Max-Age=31536000; SameSite=Lax`
62+
}
63+
6064
const LOCALES: readonly Locale[] = [
6165
"en",
6266
"zh",
@@ -199,6 +203,7 @@ export const { use: useLanguage, provider: LanguageProvider } = createSimpleCont
199203
createEffect(() => {
200204
if (typeof document !== "object") return
201205
document.documentElement.lang = locale()
206+
document.cookie = cookie(locale())
202207
})
203208

204209
return {

packages/web/src/middleware.ts

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,28 @@ function docsAlias(pathname: string) {
1212

1313
const next = locale === "root" ? `/docs${tail}` : `/docs/${locale}${tail}`
1414
if (next === pathname) return null
15-
return next
15+
return {
16+
path: next,
17+
locale,
18+
}
19+
}
20+
21+
function cookie(locale: string) {
22+
const value = locale === "root" ? "en" : locale
23+
return `oc_locale=${encodeURIComponent(value)}; Path=/; Max-Age=31536000; SameSite=Lax`
24+
}
25+
26+
function redirect(url: URL, path: string, locale?: string) {
27+
const next = new URL(url.toString())
28+
next.pathname = path
29+
const headers = new Headers({
30+
Location: next.toString(),
31+
})
32+
if (locale) headers.set("Set-Cookie", cookie(locale))
33+
return new Response(null, {
34+
status: 302,
35+
headers,
36+
})
1637
}
1738

1839
function localeFromCookie(header: string | null) {
@@ -59,9 +80,7 @@ function localeFromAcceptLanguage(header: string | null) {
5980
export const onRequest = defineMiddleware((ctx, next) => {
6081
const alias = docsAlias(ctx.url.pathname)
6182
if (alias) {
62-
const url = new URL(ctx.request.url)
63-
url.pathname = alias
64-
return ctx.redirect(url.toString(), 302)
83+
return redirect(ctx.url, alias.path, alias.locale)
6584
}
6685

6786
if (ctx.url.pathname !== "/docs" && ctx.url.pathname !== "/docs/") return next()
@@ -71,7 +90,5 @@ export const onRequest = defineMiddleware((ctx, next) => {
7190
localeFromAcceptLanguage(ctx.request.headers.get("accept-language"))
7291
if (!locale || locale === "root") return next()
7392

74-
const url = new URL(ctx.request.url)
75-
url.pathname = `/docs/${locale}/`
76-
return ctx.redirect(url.toString(), 302)
93+
return redirect(ctx.url, `/docs/${locale}/`)
7794
})

0 commit comments

Comments
 (0)