Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

next.js 14 add middleware.js short circuits "/" path #8078

Open
mocraimer opened this issue Dec 21, 2024 · 0 comments
Open

next.js 14 add middleware.js short circuits "/" path #8078

mocraimer opened this issue Dec 21, 2024 · 0 comments

Comments

@mocraimer
Copy link

[REQUIRED] Environment info

firebase-tools:
13.11.2

Platform:
Windows 11

[REQUIRED] Test case

create a next.js app (version 14.2.4) under src add middleware.json with following contents
`import { NextResponse } from 'next/server';
import { i18nConfig } from '@/app/i18n/config';

export function middleware(request) {
const { pathname } = request.nextUrl;

// Skip middleware for static files and api routes
if (
pathname.startsWith('/_next') ||
pathname.startsWith('/api') ||
pathname.includes('/assets/') ||
pathname.includes('.')
) {
return NextResponse.next();
}

// Handle root path redirects
if (pathname === '/') {
const locale = getLocale(request);
return NextResponse.redirect(new URL(/${locale}, request.url));
}

// Check if the path starts with a locale
const pathnameIsMissingLocale = i18nConfig.locales.every(
locale => !pathname.startsWith(/${locale}/) && pathname !== /${locale}
);

if (pathnameIsMissingLocale) {
const locale = getLocale(request);
return NextResponse.redirect(
new URL(/${locale}${pathname}, request.url)
);
}

return NextResponse.next();
}

export const config = {
matcher: [
'/',
'/((?!api|_next|assets|.\..).*)'
]
};

// Helper function remains the same
function getLocale(request) {
const localeCookie = request.cookies.get('NEXT_LOCALE');
if (localeCookie?.value && i18nConfig.locales.includes(localeCookie.value)) {
return localeCookie.value;
}

const acceptLanguage = request.headers.get('accept-language');
if (acceptLanguage) {
const preferredLocale = acceptLanguage
.split(',')[0]
.split('-')[0]
.toLowerCase();

if (i18nConfig.locales.includes(preferredLocale)) {
   return preferredLocale;
 }

}

return i18nConfig.defaultLocale;
}`

deploy this to a firebase hosting site (no app connected) go to "/" path of site and see you get a link to open firebase hosting, if you add any other pages you can still navigate to those.

[REQUIRED] Steps to reproduce

see above

[REQUIRED] Expected behavior

the index.js under pages folder should be rendered.

[REQUIRED] Actual behavior

you get a link to open firebase hosting, if you add any other pages you can still navigate to those.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants