-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
38 lines (29 loc) · 1.12 KB
/
middleware.ts
File metadata and controls
38 lines (29 loc) · 1.12 KB
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
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
const PUBLIC_PATHS = ['/login', '/register', '/forgot-password', '/legal']
function isPublic(pathname: string) {
return (
PUBLIC_PATHS.some((p) => pathname === p || pathname.startsWith(p + '/')) ||
pathname.startsWith('/auth/') ||
pathname.startsWith('/api/')
)
}
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
if (pathname.startsWith('/api/')) {
const apiBase = process.env.INTERNAL_API_URL ?? 'http://localhost:3001'
const target = new URL(pathname + request.nextUrl.search, apiBase)
return NextResponse.rewrite(target)
}
const hasRefreshToken = request.cookies.has('refresh_token')
if (!hasRefreshToken && !isPublic(pathname)) {
return NextResponse.redirect(new URL('/login', request.url))
}
if (hasRefreshToken && (pathname === '/login' || pathname === '/register')) {
return NextResponse.redirect(new URL('/dashboard', request.url))
}
return NextResponse.next()
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}