Guest User

Middleware

a guest
Mar 29th, 2024
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.17 KB | Source Code | 0 0
  1. import authConfig from "@/auth.config"
  2. import {
  3.   apiAuthPrefix,
  4.   authRoutes,
  5.   DEFAULT_LOGIN_REDIRECT,
  6.   publicRoutes,
  7. } from "@/routes"
  8. import NextAuth from "next-auth"
  9.  
  10. const { auth } = NextAuth(authConfig)
  11.  
  12. export default auth(req => {
  13.   const { nextUrl } = req
  14.   const isLoggedIn = !!req.auth
  15.  
  16.   const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix)
  17.   const isPublicRoute = publicRoutes.includes(nextUrl.pathname)
  18.   const isAuthRoute = authRoutes.includes(nextUrl.pathname)
  19.  
  20.   if (isApiAuthRoute) {
  21.     return
  22.   }
  23.  
  24.   if (isAuthRoute) {
  25.     if (isLoggedIn) {
  26.       return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
  27.     }
  28.     return
  29.   }
  30.  
  31.   if (!isLoggedIn && !isPublicRoute) {
  32.     let callbackUrl = nextUrl.pathname
  33.     if (nextUrl.search) {
  34.       callbackUrl += nextUrl.search
  35.     }
  36.  
  37.     const encodedCallbackUrl = encodeURIComponent(callbackUrl)
  38.  
  39.     return Response.redirect(
  40.       new URL(`/login?callbackUrl=${encodedCallbackUrl}`, nextUrl)
  41.     )
  42.   }
  43.  
  44.   return
  45. })
  46.  
  47. // Optionally, don't invoke Middleware on some paths
  48. export const config = {
  49.   matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment