Next.js Discord

Discord Forum

Next-auth and Next-intl middleware recommendation

Unanswered
MeKa posted this in #help-forum
Open in Discord
I want to do route control manually. Example: I want to restrict access to route /admin if User Role is not "ADMIN".

This sample code block is the next-intl excerpt.

import {withAuth} from 'next-auth/middleware';
import createIntlMiddleware from 'next-intl/middleware';
import {NextRequest} from 'next/server';
 
const locales = ['tr', 'en'];
const publicPages = ['/', '/login', '/register'];
 
const intlMiddleware = createIntlMiddleware({
  locales,
  defaultLocale: 'tr'
});
 
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|.*\\..*).*)', "/panel"]
};

4 Replies

@Siamese Crocodile Brother can you help me?
I understand the control structure here, but can't I do an additional manual operation? So if the user's role is "ADMIN", it can go to the "/panel" route, but if not, I want to block it.
Sun bear
@MeKa
is there any solution