Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import authConfig from "@/auth.config"
- import {
- apiAuthPrefix,
- authRoutes,
- DEFAULT_LOGIN_REDIRECT,
- publicRoutes,
- } from "@/routes"
- import NextAuth from "next-auth"
- 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
- }
- if (isAuthRoute) {
- if (isLoggedIn) {
- return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
- }
- return
- }
- if (!isLoggedIn && !isPublicRoute) {
- let callbackUrl = nextUrl.pathname
- if (nextUrl.search) {
- callbackUrl += nextUrl.search
- }
- const encodedCallbackUrl = encodeURIComponent(callbackUrl)
- return Response.redirect(
- new URL(`/login?callbackUrl=${encodedCallbackUrl}`, nextUrl)
- )
- }
- return
- })
- // Optionally, don't invoke Middleware on some paths
- export const config = {
- matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
- }
Advertisement
Add Comment
Please, Sign In to add comment