Next.js Discord

Discord Forum

middleware with next-auth and next-int(n18i)

Unanswered
cadco_ka posted this in #help-forum
Open in Discord
Is it possible to use 2 different middleware that run one after the other?
And is it recomended, because i have next-auth and that need to separate middlewares?

Can anybody give me a professional advice of this.
What i want to acomplice is simple.

But i read in different post that it is not possible to use 2 middleware files?

1 Reply

Next-intl suggested this.
Is this a good way to do it?


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

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,
localePrefix: 'as-needed',
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 .flatMap((p) => (p === '/' ? ['', '/'] : p)) .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|.\..).*)']
};