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
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:
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.
Combine Middleware Functions: Instead of exporting them separately, combine the
NextAuth
andNext-i18n-router
middleware functions into a single function. This ensures that both middleware processes are handled within the same context.Sequential Execution: Ensure that the middleware functions are executed sequentially. This can be crucial if one middleware depends on the outcome of the other.
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
: