import { NextRequestWithAuth, withAuth } from "next-auth/middleware"; import { authOptions } from "@/config/authConfig"; import { NextFetchEvent, NextResponse } from "next/server"; const PUBLIC_ROUTES = ["/login", "/logout"]; const LANG_QUERY_PARAM = "lang"; const authMiddleware = withAuth({ pages: authOptions.pages, }); export default async function middleware( req: NextRequestWithAuth, event: NextFetchEvent, ) { const langPref = req.nextUrl.searchParams.get(LANG_QUERY_PARAM); if (langPref) { // Redirect to same url without the lang query param + set cookies const newUrl = new URL(req.nextUrl); newUrl.searchParams.delete(LANG_QUERY_PARAM); const response = NextResponse.redirect(newUrl); response.cookies.set("i18next", langPref); return response; } // Matcher for using the auth middleware return PUBLIC_ROUTES.some((route) => req.nextUrl.pathname.startsWith(route)) ? NextResponse.next() // Return normal response : await authMiddleware(req, event); // Let auth middleware handle response }