-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
54 lines (45 loc) · 1.49 KB
/
Copy pathproxy.ts
File metadata and controls
54 lines (45 loc) · 1.49 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 async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
if (pathname.startsWith("/_next") || pathname === "/favicon.ico") {
return NextResponse.next()
}
const isApiRoute = pathname.startsWith("/api/")
const isLoginRoute = pathname === "/login"
const token = request.cookies.get("session")?.value
if (isLoginRoute) {
if (token) {
const { verifySession } = await import("./lib/auth")
if (await verifySession(token)) {
return NextResponse.redirect(new URL("/", request.url))
}
}
return NextResponse.next()
}
if (!token) {
if (isApiRoute) {
return new NextResponse(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
headers: { "content-type": "application/json" },
})
}
return NextResponse.redirect(new URL("/login", request.url))
}
const { verifySession } = await import("./lib/auth")
if (!(await verifySession(token))) {
if (isApiRoute) {
return new NextResponse(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
headers: { "content-type": "application/json" },
})
}
const response = NextResponse.redirect(new URL("/login", request.url))
response.cookies.set("session", "", { maxAge: 0, path: "/" })
return response
}
return NextResponse.next()
}
export const config = {
matcher: ["/((?!_next/static|_next/image).*)"],
}