Skip to content

Commit cccc35d

Browse files
committed
fix: enhance language detection in pathname processing and support Accept-Language header
1 parent 680832b commit cccc35d

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

src/index.js

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,8 @@ class CoCreateFileSystem {
8686
if (!directory.includes(".")) pathname += "/index.html";
8787
}
8888

89-
const bcp47Regex = /^\/([a-zA-Z]{2,3}(?:-[a-zA-Z0-9]{2,8})+)\//;
89+
// Match both /en/ and /en-US/ style URLs
90+
const bcp47Regex = /^\/([a-zA-Z]{2,3}(?:-[a-zA-Z0-9]{2,8})?)\//;
9091
const langMatch = pathname.match(bcp47Regex);
9192
let lang, langRegion;
9293
if (langMatch) {
@@ -95,6 +96,22 @@ class CoCreateFileSystem {
9596
let basePathname = pathname.replace("/" + langRegion, "");
9697
data.$filter.query.pathname = basePathname;
9798
} else {
99+
// No language in URL, try Accept-Language header
100+
let acceptLang = req.headers && req.headers["accept-language"];
101+
if (acceptLang) {
102+
// Parse the Accept-Language header, get the first language
103+
let preferred = acceptLang.split(",")[0].trim();
104+
if (preferred) {
105+
lang = preferred.split("-")[0];
106+
langRegion = preferred;
107+
// --- BEGIN OPTIONAL REDIRECT ---
108+
// Uncomment to enable automatic redirect to language-specific path
109+
// let newPath = `/${preferred}${pathname.startsWith('/') ? '' : '/'}${pathname.replace(/^\//, '')}`;
110+
// res.writeHead(302, { Location: newPath });
111+
// return res.end();
112+
// --- END OPTIONAL REDIRECT ---
113+
}
114+
}
98115
data.$filter.query.pathname = pathname;
99116
}
100117

@@ -195,7 +212,7 @@ class CoCreateFileSystem {
195212
try {
196213
file.urlObject = urlObject;
197214

198-
if (langRegion) {
215+
if (lang) {
199216
if (!file.languages) {
200217
file.languages = organization.languages || [
201218
langRegion

0 commit comments

Comments
 (0)