-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
30 lines (29 loc) · 925 Bytes
/
middleware.ts
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
import { NextRequest, NextResponse } from "next/server";
const privateApiRoutesRegex = new RegExp(
"/(api(?!/invaders/[^/]+/OG|/revalidate).*)"
);
export function middleware(request: NextRequest, response: NextResponse) {
const route = request.nextUrl.pathname;
if (privateApiRoutesRegex.test(route)) {
console.log("api shield triggered");
const token = request.headers.get("api-token");
if (!token || token !== process.env.API_SECRET)
return NextResponse.json(
{ message: "Unauthorized access" },
{ status: 401 }
);
}
if (new RegExp("^/map.*").test(route)) {
const res = NextResponse.next();
if (request.geo?.latitude && request.geo?.longitude)
res.cookies.set(
"geoip",
JSON.stringify({
lat: request.geo.latitude,
lng: request.geo.longitude,
})
);
else res.cookies.delete("geoip");
return res;
}
}