Skip to content

Commit 77697eb

Browse files
Copilothuangyiirene
andcommitted
Implement automatic language detection and redirection
Co-authored-by: huangyiirene <7665279+huangyiirene@users.noreply.github.com>
1 parent 00ffe80 commit 77697eb

1 file changed

Lines changed: 43 additions & 2 deletions

File tree

app/page.tsx

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,46 @@
11
import { redirect } from 'next/navigation';
2+
import { headers } from 'next/headers';
3+
import { i18n } from '@/lib/i18n';
24

3-
export default function HomePage() {
4-
redirect('/en/docs');
5+
export default async function HomePage() {
6+
const headersList = await headers();
7+
const acceptLanguage = headersList.get('accept-language') || '';
8+
9+
// Parse the Accept-Language header and find the best match
10+
const preferredLang = getPreferredLanguage(acceptLanguage, i18n.languages);
11+
12+
redirect(`/${preferredLang}/docs`);
13+
}
14+
15+
function getPreferredLanguage(acceptLanguage: string, availableLanguages: readonly string[]): string {
16+
// Parse Accept-Language header (e.g., "zh-CN,zh;q=0.9,en;q=0.8")
17+
const languages = acceptLanguage
18+
.split(',')
19+
.map(lang => {
20+
const parts = lang.trim().split(';');
21+
const code = parts[0];
22+
const quality = parts[1] ? parseFloat(parts[1].split('=')[1]) : 1.0;
23+
return { code, quality };
24+
})
25+
.sort((a, b) => b.quality - a.quality);
26+
27+
// Try to find the best match (exact or partial) respecting quality order
28+
for (const lang of languages) {
29+
// Try exact match first
30+
if (availableLanguages.includes(lang.code)) {
31+
return lang.code;
32+
}
33+
34+
// Try partial match (e.g., "zh" matches "zh-CN")
35+
const langPrefix = lang.code.split('-')[0].toLowerCase();
36+
const match = availableLanguages.find(available =>
37+
available.toLowerCase().startsWith(langPrefix)
38+
);
39+
if (match) {
40+
return match;
41+
}
42+
}
43+
44+
// Default to the configured default language
45+
return i18n.defaultLanguage;
546
}

0 commit comments

Comments
 (0)