2

I don't know how to use 'next-auth/middleware' and 'next-intl/middleware' together in the middleware. Next-auth gets exported as default and it's a must... on the other hand Next-intl creates a middleware and add a separate config...

export { default } from "next-auth/middleware";

export const config = {
  matcher: ["/((?!register|api|login).*)"],
};

import createMiddleware from "next-intl/middleware";

export default createMiddleware({
  locales: ["en", "es"],

  defaultLocale: "en",
});

export const config = {
  // Skip all paths that should not be internationalized
  matcher: ["/((?!api|_next|.*\\..*).*)"],
};

I tried to search on google to use these two together but there was no blog. I don't know how these two are going to be in a single middleware export

Wali ahmed
  • 21
  • 2

2 Answers2

2

There is a new examples:

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

However, make sure "next" version is 13.4.6 and up. For example:

npm install next@13.4.6
Luke Tsang
  • 21
  • 1
0

Here at: Composing other middlewares Nextintl you can find more details.

import {withAuth} from 'next-auth/middleware';
import createIntlMiddleware from 'next-intl/middleware';
import {NextRequest} from 'next/server';
 
const locales = ['en', 'de'];
const publicPages = ['/', '/login'];
 
const intlMiddleware = createIntlMiddleware({
  locales,
  defaultLocale: 'en'
});
 
const authMiddleware = withAuth(
  // Note that this callback is only invoked if
  // the `authorized` callback has returned `true`
  // and not for pages listed in `pages`.
  function onSuccess(req) {
    return intlMiddleware(req);
  },
  {
    callbacks: {
      authorized: ({token}) => token != null
    },
    pages: {
      signIn: '/login'
    }
  }
);
 
export default function middleware(req: NextRequest) {
  const publicPathnameRegex = RegExp(
    `^(/(${locales.join('|')}))?(${publicPages.join('|')})?/?$`,
    'i'
  );
  const isPublicPage = publicPathnameRegex.test(req.nextUrl.pathname);
 
  if (isPublicPage) {
    return intlMiddleware(req);
  } else {
    return (authMiddleware as any)(req);
  }
}
 
export const config = {
  matcher: ['/((?!api|_next|.*\\..*).*)']
};