Issue middleware redirect on login
Unanswered
Zepeto posted this in #help-forum
ZepetoOP
Hi I'm using next-auth and next-intl
I had to use the advanced method of the middleware to be able to block the application to non connected users.
However when I log in successfully I am not always redirected to the home page. (redirecting with router.push)
The token is null in the middleware and it considers me as not authenticated, but I can see my username in the nav bar at the top.
I had to use the advanced method of the middleware to be able to block the application to non connected users.
However when I log in successfully I am not always redirected to the home page. (redirecting with router.push)
The token is null in the middleware and it considers me as not authenticated, but I can see my username in the nav bar at the top.
import { withAuth } from "next-auth/middleware";
import createMiddleware from "next-intl/middleware";
import { NextMiddlewareResult } from "next/dist/server/web/types";
import {
NextFetchEvent,
NextMiddleware,
NextRequest,
NextResponse,
} from "next/server";
const locales = ["en", "de"];
const publicPages = ["/login"];
const intlMiddleware = createMiddleware({
locales: locales,
defaultLocale: "en",
});
type NextMiddlewareWithRequest = (request: NextRequest) => NextMiddlewareResult;
const authMiddleware = (
req: NextRequest,
event: NextFetchEvent,
otherMiddleware?: NextMiddlewareWithRequest
) =>
(
withAuth(
(r: NextRequest) =>
otherMiddleware ? otherMiddleware(r) : NextResponse.next(),
{
callbacks: {
authorized: ({ token }) => {
console.log("token", token);
return Boolean(token);
},
},
pages: {
signIn: "/login",
},
}
) as NextMiddleware
)(req, event);
export default function middleware(req: NextRequest, event: NextFetchEvent) {
const publicPathnameRegex = RegExp(
`^(/(${locales.join("|")}))?(${publicPages.join("|")})/?$`,
"i"
);
const isPublicPage = publicPathnameRegex.test(req.nextUrl.pathname);
if (isPublicPage) {
return intlMiddleware(req);
} else {
return authMiddleware(req, event, intlMiddleware);
}
}
export const config = {
matcher: ["/((?!api|_next|.*\\..*).*)"],
};