```import { NextRequest, NextResponse } from "next/server"; import { betterFetch } from "@better-fetch/fetch"; import createMiddleware from "next-intl/middleware"; import { auth } from "~/lib/auth"; import { routing } from "./i18n/routing"; type Session = typeof auth.$Infer.Session; const intlMiddleware = createMiddleware(routing); // Helper to check if path should be protected const isProtectedRoute = (pathname: string) => { // Remove locale prefix if present (e.g., /en/dashboard -> /dashboard) const pathWithoutLocale = pathname.replace(/^\/(?:ro|en)/, ""); return pathWithoutLocale.startsWith("/dashboard"); }; export default async function middleware(request: NextRequest) { const pathname = request.nextUrl.pathname; // Check if this is a protected route before handling i18n if (isProtectedRoute(pathname)) { try { const { data: session } = await betterFetch( "/api/auth/get-session", { baseURL: request.nextUrl.origin, headers: { cookie: request.headers.get("cookie") || "", }, }, ); if (!session) { // Get locale from URL or default to 'en' const locale = pathname.match(/^\/(?:ro|en)/)?.[0]?.replace("/", "") || "en"; return NextResponse.redirect( new URL(`/${locale}/sign-in`, request.url), ); } } catch (error) { // Handle any authentication errors const locale = pathname.match(/^\/(?:ro|en)/)?.[0]?.replace("/", "") || "en"; return NextResponse.redirect(new URL(`/${locale}/sign-in`, request.url)); } } // Handle internationalization after authentication check return intlMiddleware(request); } export const config = { matcher: [ // Enable a redirect to a matching locale at the root "/", // Set a cookie to remember the previous locale for // all requests that have a locale prefix "/(ro|en)/:path*", // Enable redirects that add missing locales // (e.g. `/pathnames` -> `/en/pathnames`) "/((?!api|_next|_vercel|.*\\..*).*)", // protected routes "/dashboard/:path*", "/(ro|en)/dashboard/:path*", ], }; ```