Next.js Discord

Discord Forum

Middleware

Unanswered
Rahul the Developer posted this in #help-forum
Open in Discord
How to apply middleware for dynamic route if hit ignore middleware in nextjs where I am using next-auth v5 beta

This is my middleware file code:
import NextAuth from "next-auth";

import { authConfig } from "@/app/api/auth/[...nextauth]/auth.config";
import {
authRoutes,
apiAuthPrefix,
publicRoutes,
DEFAULT_LOGIN_REDIRECT,
DEFAULT_REDIRECT,
} from "@/routes";

const { auth } = NextAuth(authConfig);

export default auth((req) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;

const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
const isAuthRoute = authRoutes.includes(nextUrl.pathname);

if (isApiAuthRoute) return null;

if (isAuthRoute) {
if (isLoggedIn) {
return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl));
}
return null;
}

if (!isLoggedIn && !isPublicRoute) {
let callbackUrl = nextUrl.pathname;
if (nextUrl.search) {
callbackUrl += nextUrl.search;
}
const encodedCallbackUrl = encodeURIComponent(callbackUrl);

return Response.redirect(
new URL(/login?callback=${encodedCallbackUrl}, nextUrl)
);
}

return null;
});

export const config = {
matcher: ["/((?!.+\.[\w]+$|_next).)", "/", "/(api|trpc)(.)"],
};

This is my routes file code where I have declare publicRoutes, authRoutes and etc.:
export const publicRoutes = ["/:username", "/verificationtoken"];
export const authRoutes = ["/login", "/reset/password", "/change-password"];
export const apiAuthPrefix = "/api/auth";
export const DEFAULT_LOGIN_REDIRECT = "/";
export const DEFAULT_REDIRECT = "/login";

0 Replies