Add automatic language detection from Accept-Language header#29
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Co-authored-by: huangyiirene <7665279+huangyiirene@users.noreply.github.com>
Co-authored-by: huangyiirene <7665279+huangyiirene@users.noreply.github.com>
🚀 Preview DeploymentThis pull request will be automatically deployed to Vercel. Preview Links
Build StatusCheck the CI workflow for build status and any errors. Automated preview information for PR #29 |
There was a problem hiding this comment.
Pull request overview
This PR adds automatic language detection to redirect users to documentation in their preferred language based on the Accept-Language HTTP header, replacing the previous hardcoded English redirect.
Changes:
- Modified root page handler to be async and parse the
Accept-Languageheader - Implemented
getPreferredLanguagefunction with quality value parsing and locale matching logic - Added fallback behavior to default language when no match is found
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // Try exact match first | ||
| if (availableLanguages.includes(lang.code)) { | ||
| return lang.code; |
There was a problem hiding this comment.
Case-sensitive comparison may fail to match language codes. The Accept-Language header can contain mixed case (e.g., 'en-US', 'EN-us'), but this performs exact case-sensitive matching. Consider normalizing both the lang.code and availableLanguages entries to lowercase before comparison to ensure reliable matching.
| // Try exact match first | |
| if (availableLanguages.includes(lang.code)) { | |
| return lang.code; | |
| // Try exact match first (case-insensitive) | |
| const exactMatch = availableLanguages.find( | |
| available => available.toLowerCase() === lang.code.toLowerCase() | |
| ); | |
| if (exactMatch) { | |
| return exactMatch; |
| redirect(`/${preferredLang}/docs`); | ||
| } | ||
|
|
||
| function getPreferredLanguage(acceptLanguage: string, availableLanguages: readonly string[]): string { |
There was a problem hiding this comment.
The getPreferredLanguage function lacks test coverage for critical edge cases including empty Accept-Language headers, malformed quality values, case sensitivity handling, and fallback behavior. Consider adding unit tests to verify correct behavior across these scenarios.
The documentation site hardcoded a redirect to
/en/docs, ignoring users' browser language preferences.Implementation
Modified root page to parse
Accept-Languageheader and redirect to best matching locale:Language Matching Logic
zh-CN;q=0.9,en;q=0.8) and sorts by preferencezh-CN)zh→zh-CN)Behavior
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8→/zh-CN/docsAccept-Language: en-US,en;q=0.9→/en/docsAccept-Language: fr-FR→/en/docs(fallback)/en/docs(fallback)Original prompt
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.