Skip to content

Commit

Permalink
Core: Fix search params being ignored in middleware redirection
Browse files Browse the repository at this point in the history
  • Loading branch information
fuma-nama committed Jan 14, 2025
1 parent 7930af1 commit bb73a72
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changeset/few-clouds-fly.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'fumadocs-core': patch
---

Fix search params being ignored in middleware redirection
24 changes: 14 additions & 10 deletions packages/core/src/i18n/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ function getLocale(
): string {
// Negotiator expects plain object so we need to transform headers
const negotiatorHeaders: Record<string, string> = {};
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value));
request.headers.forEach((value, key) => {
negotiatorHeaders[key] = value;
});

// Use negotiator and intl-localematcher to get best locale
const languages = new Negotiator({ headers: negotiatorHeaders }).languages(
Expand Down Expand Up @@ -62,31 +64,33 @@ export function createI18nMiddleware({
}

return (request) => {
const { pathname } = request.nextUrl;
const inputPath = `${request.nextUrl.pathname}${request.nextUrl.search}`;

const pathLocale = languages.find(
(locale) =>
pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`,
inputPath.startsWith(`/${locale}/`) || inputPath === `/${locale}`,
);

if (!pathLocale) {
if (hideLocale === 'default-locale') {
return NextResponse.rewrite(getUrl(request, pathname, defaultLanguage));
return NextResponse.rewrite(
getUrl(request, inputPath, defaultLanguage),
);
}

const preferred = getLocale(request, languages, defaultLanguage);

if (hideLocale === 'always') {
const locale = request.cookies.get(COOKIE)?.value ?? preferred;

return NextResponse.rewrite(getUrl(request, pathname, locale));
return NextResponse.rewrite(getUrl(request, inputPath, locale));
}

return NextResponse.redirect(getUrl(request, pathname, preferred));
return NextResponse.redirect(getUrl(request, inputPath, preferred));
}

if (hideLocale === 'always') {
const path = pathname.slice(`/${pathLocale}`.length);
const path = inputPath.slice(`/${pathLocale}`.length);

const res = NextResponse.redirect(getUrl(request, path));
res.cookies.set(COOKIE, pathLocale);
Expand All @@ -96,9 +100,9 @@ export function createI18nMiddleware({
// Remove explicit default locale
// (Only possible for default locale)
if (hideLocale === 'default-locale' && pathLocale === defaultLanguage) {
const path = pathname.slice(`/${pathLocale}`.length);

return NextResponse.redirect(getUrl(request, path));
return NextResponse.redirect(
getUrl(request, inputPath.slice(`/${pathLocale}`.length)),
);
}

return NextResponse.next();
Expand Down

0 comments on commit bb73a72

Please sign in to comment.