-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
36 lines (27 loc) · 1.03 KB
/
Copy pathproxy.ts
File metadata and controls
36 lines (27 loc) · 1.03 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const ADMIN_COOKIE = "admin_session";
export function proxy(request: NextRequest) {
const { pathname, search } = request.nextUrl;
if (pathname === "/api/admin/login" || pathname === "/admin/login") {
return NextResponse.next();
}
if (pathname.startsWith("/admin") && process.env.NODE_ENV === "production") {
return NextResponse.redirect(new URL("/", request.url));
}
const secret = process.env.ADMIN_SECRET;
const cookie = request.cookies.get(ADMIN_COOKIE)?.value;
const authorized = Boolean(secret) && cookie === secret;
if (authorized) {
return NextResponse.next();
}
if (pathname.startsWith("/api/admin")) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const loginUrl = new URL("/admin/login", request.url);
loginUrl.searchParams.set("next", pathname + search);
return NextResponse.redirect(loginUrl);
}
export const config = {
matcher: ["/admin/:path*", "/api/admin/:path*"],
};