-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
35 lines (28 loc) · 1.01 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import NextAuth from "next-auth"
import { NextResponse } from "next/server"
import authConfig from "@/lib/auth.config"
const protectedRoutes = ["/dashboard", "/settings"]
const authRoutes = ["/login", "/register", "/auth/reset", "/auth/new-password"]
const mainRoute = ["/"]
const { auth } = NextAuth(authConfig)
export default auth((req) => {
const { nextUrl } = req
const path = nextUrl.pathname
const isLoggedIn = !!req.auth
const isProtectedRoute = protectedRoutes.some((route) =>
path.startsWith(route)
)
const isAuthRoute = authRoutes.includes(path)
const isMainRoute = mainRoute.includes(path)
if (isProtectedRoute && !isLoggedIn) {
const redirectUrl = new URL("/login", nextUrl)
return NextResponse.redirect(redirectUrl)
}
if ((isAuthRoute && isLoggedIn) || (isMainRoute && isLoggedIn)) {
const redirectUrl = new URL("/dashboard", nextUrl)
return NextResponse.redirect(redirectUrl)
}
})
export const config = {
matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
}