-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
55 lines (45 loc) · 1.79 KB
/
middleware.ts
File metadata and controls
55 lines (45 loc) · 1.79 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
export default function middleware(request: NextRequest) {
// Get the pathname of the request
const path = request.nextUrl.pathname
// Define paths that should be protected
const protectedPaths = ["/dashboard"]
// Define paths that are only accessible to non-authenticated users
const authPaths = ["/auth/login", "/auth/register", "/auth/forgot-password"]
// Check if the path is protected
const isProtectedPath = protectedPaths.some((pp) => path.startsWith(pp))
const isAuthPath = authPaths.some((ap) => path === ap)
// Get the token from cookies
const token = request.cookies.get("accessToken")?.value
// Redirect logic
if (isProtectedPath && !token) {
// Redirect to login if trying to access protected route without token
// Store the original URL as a query parameter for redirect after login
const loginUrl = new URL("/auth/login", request.url)
// Only set redirect if it's not already a login path to avoid loops
if (!authPaths.some(ap => path === ap)) {
loginUrl.searchParams.set("redirect", path)
}
return NextResponse.redirect(loginUrl)
}
if (isAuthPath && token) {
// Redirect to dashboard overview if trying to access auth routes with token
return NextResponse.redirect(new URL("/dashboard/overview", request.url))
}
return NextResponse.next()
}
// Configure the paths that will trigger the middleware
export const config = {
matcher: [
/*
* Match all request paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - images (public images)
* - fonts (public fonts)
*/
"/((?!_next/static|_next/image|favicon.ico|images|fonts).*)",
],
}