|
| 1 | +import { NextResponse } from "next/server" |
| 2 | +import createMiddleware from "next-intl/middleware" |
| 3 | + |
| 4 | +import { routing } from "./src/i18n/routing" |
| 5 | + |
| 6 | +// Create the base middleware |
| 7 | +const intlMiddleware = createMiddleware(routing) |
| 8 | + |
| 9 | +// Wrap it with our debugging middleware |
| 10 | +export default async function middleware(request) { |
| 11 | + // Use console.log for Edge Runtime compatible logging |
| 12 | + console.log("\n🔍 MIDDLEWARE DEBUG START") |
| 13 | + console.log(`📥 Original URL: ${request.url}`) |
| 14 | + console.log(`📥 Original pathname: ${request.nextUrl.pathname}`) |
| 15 | + console.log(`🌐 Default locale: ${routing.defaultLocale}`) |
| 16 | + |
| 17 | + // Skip middleware for static files and API routes |
| 18 | + if ( |
| 19 | + request.nextUrl.pathname.startsWith("/_next") || |
| 20 | + request.nextUrl.pathname.startsWith("/api") || |
| 21 | + request.nextUrl.pathname.includes(".") |
| 22 | + ) { |
| 23 | + console.log("⏭️ Skipping middleware for static/API route") |
| 24 | + return NextResponse.next() |
| 25 | + } |
| 26 | + |
| 27 | + // Check if path already has a locale |
| 28 | + const pathname = request.nextUrl.pathname |
| 29 | + const pathnameHasLocale = routing.locales.some( |
| 30 | + (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}` |
| 31 | + ) |
| 32 | + |
| 33 | + if (pathnameHasLocale) { |
| 34 | + console.log("⏭️ Path already has locale, skipping middleware") |
| 35 | + return NextResponse.next() |
| 36 | + } |
| 37 | + |
| 38 | + // Force redirect to default locale for root path |
| 39 | + if (pathname === "/") { |
| 40 | + const response = NextResponse.redirect( |
| 41 | + new URL(`/${routing.defaultLocale}`, request.url) |
| 42 | + ) |
| 43 | + console.log(`📤 Redirecting root to: ${routing.defaultLocale}`) |
| 44 | + return response |
| 45 | + } |
| 46 | + |
| 47 | + // Call the next-intl middleware for all other paths |
| 48 | + const response = await intlMiddleware(request) |
| 49 | + |
| 50 | + // Log the response |
| 51 | + console.log(`📤 Redirect URL: ${response.headers.get("location")}`) |
| 52 | + console.log(`📤 Response status: ${response.status}`) |
| 53 | + console.log( |
| 54 | + `📤 Response headers: ${JSON.stringify(Object.fromEntries(response.headers), null, 2)}` |
| 55 | + ) |
| 56 | + console.log("🔍 MIDDLEWARE DEBUG END\n") |
| 57 | + |
| 58 | + return response |
| 59 | +} |
| 60 | + |
| 61 | +// Simplified matcher pattern |
| 62 | +export const config = { |
| 63 | + matcher: ["/((?!api|_next|_vercel|.*\\.[^/]*$).*)"], |
| 64 | +} |
0 commit comments