create-auth-js-boiler
Version:
Create a new auth-js-boiler project
50 lines (44 loc) • 1.42 kB
text/typescript
import NextAuth from "next-auth";
import authConfig from "./auth.config";
import {
DEFAULT_LOGIN_REDIRECT,
apiAuthPrefix,
authRoutes,
publicRoutes,
} 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) {
// Do nothing for API auth routes
return null;
}
if (isAuthRoute) {
if (isLoggedIn) {
// Redirect logged-in users away from auth routes
return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl));
}
// Allow unauthenticated users to access auth routes
return null;
}
if (!isLoggedIn && !isPublicRoute) {
// Redirect unauthenticated users to the login page
let callbackUrl = nextUrl.pathname;
if (nextUrl.search) {
callbackUrl += nextUrl.search;
}
const encodedCallbackUrl = encodeURIComponent(callbackUrl);
return Response.redirect(
new URL(`/auth/login?callbackUrl=${encodedCallbackUrl}`, nextUrl),
);
}
// // we can here return null if we didn't want to use path in server side comp
return null;
});
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};