skip to Main Content

I’m currently working on a Next.js 14 app that utilizes NextAuth for authentication and Next-i18n-router for translations. I have followed the documentation for both libraries, but I’m encountering an issue with the middleware configuration.

The problem is that the middleware from NextAuth seems to stop working when combined with the middleware from Next-i18n-router. I’ve followed the documentation for both libraries, but it’s possible that I missed something or there’s a conflict.

Here’s my code:

// middleware.ts
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
import { i18nRouter } from 'next-i18n-router';
import i18nConfig from './i18nConfig';
import { NextRequest } from 'next/server';

export default NextAuth(authConfig).auth;

export function middleware(request: NextRequest) {
  return i18nRouter(request, i18nConfig);
}

// only applies this middleware to files in the app directory
export const config = {
  matcher: ['/((?!api|_next/static|_next/image|.*\.png$).*)'],
};

2

Answers


  1. Chosen as BEST ANSWER

    the @Batman answer helped me, just needed to change a little the auth method, this is the code updated for new users with the same problem:

    const protectedRoutes = ['/dashboard'];
    const authRoutes = ['/login'];
    
    export async function middleware(request: NextRequest) {
      try {
        const authResponse = await NextAuth(authConfig).auth();
        const isAuthenticated: boolean = Boolean(authResponse?.user);
        if (
          !isAuthenticated &&
          protectedRoutes.includes(request.nextUrl.pathname)
        ) {
          return NextResponse.redirect(new URL('/', request.url));
        } else if (
          isAuthenticated &&
          authRoutes.includes(request.nextUrl.pathname)
        ) {
          // TODO should return to previous route, not only dashboard
          return NextResponse.redirect(new URL('/dashboard', request.url));
        }
        return i18nRouter(request, i18nConfig);
      } catch (error) {
        console.error('Middleware Error:', error);
        return new NextResponse('Internal Server Error', { status: 500 });
      }
    }
    

  2. You might be facing an issue with the integration of NextAuth and Next-i18n-router in your Next.js application. Middleware in Next.js can sometimes have conflicts or issues if not configured correctly, especially when integrating multiple middleware functionalities.

    1. Combine Middleware Functions: Instead of exporting them separately, combine the NextAuth and Next-i18n-router middleware functions into a single function. This ensures that both middleware processes are handled within the same context.

    2. Sequential Execution: Ensure that the middleware functions are executed sequentially. This can be crucial if one middleware depends on the outcome of the other.

    3. Error Handling: Add error handling to catch and resolve any issues that arise during middleware execution.

    Here’s an example of how you might revise your middleware.ts:

    import NextAuth from 'next-auth';
    import { authConfig } from './auth.config';
    import { i18nRouter } from 'next-i18n-router';
    import i18nConfig from './i18nConfig';
    import { NextRequest, NextResponse } from 'next/server';
    
    export async function middleware(request: NextRequest) {
      try {
        // First, handle authentication
        const authResponse = await NextAuth(authConfig).auth(request);
        if (authResponse instanceof NextResponse && !authResponse.ok) {
          return authResponse; // If auth fails, return the response
        }
    
        // Then, handle internationalization
        const i18nResponse = i18nRouter(request, i18nConfig);
        return i18nResponse;
      } catch (error) {
        // Handle any errors that occur during middleware execution
        console.error("Middleware Error:", error);
        return new NextResponse("Internal Server Error", { status: 500 });
      }
    }
    
    export const config = {
      matcher: ['/((?!api|_next/static|_next/image|.*\.png$).*)'],
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search