Middleware Issue Review (VERCEL)
Repo
https://github.com/miniu-jacob/next-ccunion.git
Overview
- After deploying to Vercel, an issue occurs where the language setting resets when I change the language and navigates to a different link.
Background
Environment: next.js 15 with Turbo, next-intl for multilingual support, Vercel deployment
"next": "15.1.7", "react": "^19.0.0", "next-intl": "^3.26.3",Problem Situation: When a user changes the language (e.g., from ko to en) and navigates to another link, the language reverts to the default (e.g., ko or en).
In a similar e-commerce project, no issues occurred when using the component from next/link in the header.
Works correctly locally, but the issue only occurs in the Vercel deployment environment.
Related Code
middleware: Integration of next-intl and next-auth, handling language and authentication logic.
i18n/routing.ts: Routing configuration for next-intl (localePrefix: "as-needed").
Cause Analysis
Client-Server State Inconsistency:
Developer Tools → Inspect → Network Logs
/ko/about → 307 Temporary Redirect → /about
/ko/about → /about, next-Url: /vn/about → Confirmed that the client maintains the previous language (vn).
- Location: Client router (next-Url - observable in the network request headers in developer tools).
/about → next-Url: /vn/about persists → Next request goes to /vn.
Suspected Cause
- Inconsistency between the client router state (next-Url) and the server middleware.
Actions for Problem Resolution
1. What I have tried
// i18n/routing.ts localeCookie: { name: "NEXT_LOCALE" }, // <--- did not solvelocaleDetection: false, // <--- did not solvelocalePrefix: { mode: "as-needed" }, // <--- did not solvelocalePrefix: { mode: "as-needed", { prefixes: { "ko": "/", "en": "/en", "vn": "/vn", } }, // <--- did not solvelocalePrefix: { mode: "always", { prefixes: { "ko": "/ko", "en": "/en", "vn": "/vn", } }, // <--- did not solvelocalePrefix: "always", // <--- did not solvepathnames: { ... }, // <--- did not solvei18n/routing.ts file code
// i18n/routing.tsimport { routesData } from "@/lib/db/data/routes-data";import { createNavigation } from "next-intl/navigation";import { defineRouting } from "next-intl/routing";// routesData 에서 모든 경로 추출const allPaths = [ ...routesData.public.static, ...routesData.public.dynamic, ...routesData.protected.static, ...routesData.protected.dynamic,];const pathnames = Object.fromEntries(allPaths.map((path) => [path, path]));/* ROUTING CONFIGURATION * ============================= * [Step D] Routing 설정을 정의한다. * - locales: 언어 목록 * - defaultLocale: 기본 언어 * - localeCookie: 쿠키 설정 (선택) * - localePrefix: 언어별 prefix 설정 - 모드 설정 시 pathnames와 관계 없이 prefix 설정 * - pathnames: URL 경로가 다른 경우 필요 * ============================= */export const routing = defineRouting({ locales: ["ko", "en", "vn"], defaultLocale: "ko", // localeDetection: false, // localeCookie: { name: "NEXT_LOCALE" }, localePrefix: "always", pathnames,});export const { Link, redirect, usePathname, useRouter } = createNavigation(routing);Here's the middleware code.
middleware.ts
// middleware.tsimport createMiddleware from "next-intl/middleware";import { routing } from "./i18n/routing";import NextAuth from "next-auth";import authConfig from "./lib/auth.config";import { protectedPaths, publicPaths } from "./lib/db/data/routes-data";import { NextResponse } from "next/server";import { isMatch } from "./lib/utils";/* 다국어 미들웨어 생성(routing 객체 전달, createMiddleware 함수 사용) * ========================================= * [Pre-A] next-intl / next-auth 설정 * ========================================= */const intlMiddleware = createMiddleware(routing);// nextAuth 인증 미들웨어 래퍼const { auth } = NextAuth(authConfig);/* ####### MIDDLEWARE FUNCTION ####### * ========================================= * MAIN MIDDLEWARE * ========================================= */export default auth((req) => { // [Step A] next-intl 미들웨어 (rewrite/locale 설정 등) 먼저 실행 const { pathname } = req.nextUrl; const locales = routing.locales; const defaultLocale = routing.defaultLocale;Language-switcher.tsx file code
// components/shared/header/language-switcher.tsx"use client";import * as React from "react";import { DropdownMenu, DropdownMenuContent, DropdownMenuLabel, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { i18n } from "@/i18n-config";import { Link, usePathname } from "@/i18n/routing";import { useLocale } from "next-intl";import Image from "next/image";/** * 브라우저에서 NEXT_LOCALE 쿠키를 세팅하는 함수 * - maxAge: 1년 (필요하면 조정) * - Secure: HTTPS 환경에서만 전송 (Vercel이라면 보통 자동 HTTPS) * - SameSite=Lax */export function cleanPathname(pathname: string, locale: string) { const localePrefix = `/${locale}`; return pathname.startsWith(localePrefix) ? pathname.replace(localePrefix, "") || "/" : pathname;}Header
// components/shared/header/index.tsximport Link from "next/link";import { buttonVariants } from "@/components/ui/button";import { ThemeToggleButton } from "./theme-toggle-button";import { SideSheet } from "./side-sheet";import data from "@/lib/db/data/data";import LanguageSwitcher from "./language-switcher";import { useLocale } from "next-intl";export default function Header() { const locale = useLocale(); console.log("[DEBUG] Header - locale: ", locale); return ( <header className="h-16 bg-background/40 sticky top-0 border-b px-8 backdrop-blur-sm flex items-center justify-between"> {/* HEADER - 1: LOGO */} <div className="flex items-center"> <Link href={"/"}> <h1 className="font-bold text-lg md:text-xl text-nowrap">CCB Alliance</h1> </Link> </div> {/* HEADER -2: MENUS */} <div className="hidden md:flex w-full justify-end space-x-4 items-center"> {data.headerMenus.map((menu) => ( <Link key={menu.href} href={`${menu.href}`} className="text-base p-2"> {menu.name} </Link> ))} </div>