-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
41 lines (30 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
36
37
38
39
40
41
import authConfig from '@/app/auth.config'
import NextAuth from 'next-auth'
type PathMatcher = (route: string) => boolean
const { auth } = NextAuth(authConfig)
export default auth(req => {
const { pathname: urlPathname } = req.nextUrl
const isAuthRoute = urlPathname.startsWith('/auth')
const isApiAuthRoute = urlPathname.startsWith('/api/auth')
const isLoggedIn = !!req.auth
const pathMatcher: PathMatcher = route => {
const withoutStarRoute = route.slice(0, -1)
return route.at(-1) === '*' ? urlPathname.startsWith(withoutStarRoute) : urlPathname === route
}
const doRedirection: (url: string) => Response = url => Response.redirect(new URL(url, req.nextUrl))
if(isLoggedIn) {
if(isAuthRoute)
return doRedirection('/')
return null
}
if(isApiAuthRoute || publicRoutes.some(pathMatcher))
return null
return doRedirection('/auth/signin')
})
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"]
}
const publicRoutes = [
'/',
'/posts*'
]