Search code examples
reactjsnext.jslocalizationmiddlewarenext-intl

Combining Next-Intl and Supabase Middleware in Next JS Router


I have a NExt JS project using the app router with Supabase.

I have a ROOT middleware.js file that contains some supabase code. I also need to integrate Next-Intl middleware into this too and i'm not sure how to go about it.

Here is my ROOT middleware.js code;

export async function middleware(request: NextRequest) {
  return await updateSession(request);
}

export const config = {
  matcher: [
    "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
  ],
};

From what I understand (limited) I need to use the following somewhere;

import createMiddleware from 'next-intl/middleware';
 
export default createMiddleware({
  // A list of all locales that are supported
  locales: ['en', 'de'],
 
  // Used when no locale matches
  defaultLocale: 'en'
});
 
export const config = {
  // Match only internationalized pathnames
  matcher: ['/', '/(de|en)/:path*']
};

Solution

  • You can call intlMiddleware inside your middleware function. This function is the primary middleware run on every request.

    const intlMiddleware = createMiddleware({
      // A list of all locales that are supported
      locales: ['en', 'de'],
      
      // Used when no locale matches
      defaultLocale: 'en'
    });
    
    export async function middleware(request: NextRequest) {
    
      const intlResponse = intlMiddleware(request);
      if (intlResponse) {
        return intlResponse;
      }
    
      return await updateSession(request);
    }
    

    And you can adjust your config by merging both these:

    export const config = {
      matcher: [
        '/', 
        '/(de|en)/:path*',
        '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'
      ],
    };
    

    If you only want to apply certain middleware functions for certain paths, check out these resources:

    https://nextjs.org/docs/messages/nested-middleware How to use multiple middlewares in Next.js using the middleware.ts file?