-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
25 lines (20 loc) · 856 Bytes
/
middleware.ts
File metadata and controls
25 lines (20 loc) · 856 Bytes
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
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
const authToken = request.cookies.get('auth-token')
const isAuthenticated = !!authToken
const isAuthPage = request.nextUrl.pathname.startsWith('/login')
const isProtectedPage = request.nextUrl.pathname.startsWith('/dashboard')
// Redirect to login if trying to access protected page without auth
if (isProtectedPage && !isAuthenticated) {
return NextResponse.redirect(new URL('/login', request.url))
}
// Redirect to dashboard if trying to access login page while authenticated
if (isAuthPage && isAuthenticated) {
return NextResponse.redirect(new URL('/dashboard', request.url))
}
return NextResponse.next()
}
export const config = {
matcher: ['/dashboard/:path*', '/login']
}