next.jsnext-authnext-intl

How to Combine NextAuth(v5) and Next-Intl Middleware in Next.js(app route)


I'm working on a Next.js application that uses NextAuth(v5) for authentication and Next-Intl for internationalization. I need to combine these functionalities seamlessly. Here's what I've tried so far:

Current Middleware:

import NextAuth from "next-auth";
import { authConfig } from "src/app/auth.config";

export default NextAuth(authConfig).auth;

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
};

Previous Approach (Not Applicable in NextAuth v5):

import { withAuth } from 'next-auth/middleware'; // Deprecated in NextAuth v5

// ... (middleware logic using withAuth, not applicable in v5)

https://next-intl-docs.vercel.app/docs/routing/middleware#example-auth-js

Explanation:


Solution

  • This works:

    middleware.js

    import createMiddleware from "next-intl/middleware";
    import { NextResponse } from "next/server";
    
    const internationalizationMiddleware = createMiddleware({
      locales: ["en", "de"],
      defaultLocale: "de",
    });
    
    export async function middleware(request) {
      let response = NextResponse.next();
    
      // Exclude specific paths from further processing
      if (
        !request.nextUrl.pathname.startsWith("/login") &&
        !request.nextUrl.pathname.startsWith("/api") &&
        !request.nextUrl.pathname.startsWith("/_next") &&
        !request.nextUrl.pathname.includes(".")
      ) {
        return internationalizationMiddleware(request);
      }
      // Return the response object directly
      return response;
    }
    
    export const config = {
      matcher: ["/((?!api|_next|_vercel|.*\\..*).*)"],
    };
    

    auth.js

    import NextAuth from "next-auth";
    import github from "next-auth/providers/github";
    
    export const { auth, handlers, signIn, signOut, update } = NextAuth(() => {
      return {
        secret: process.env.AUTH_SECRET,
        debug: false,
        basePath: "/api/auth",
        providers: [github]
      };
    });