-
Notifications
You must be signed in to change notification settings - Fork 4
/
middleware.ts
45 lines (42 loc) · 1.17 KB
/
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export async function middleware(request: NextRequest): Promise<NextResponse> {
if (request.method === "GET") {
const response = NextResponse.next();
const token = request.cookies.get("session")?.value ?? null;
if (token !== null) {
// Only extend cookie expiration on GET requests since we can be sure
// a new session wasn't set when handling the request.
response.cookies.set("session", token, {
path: "/",
maxAge: 60 * 60 * 24 * 30,
sameSite: "lax",
httpOnly: true,
secure: process.env.NODE_ENV === "production"
});
}
return response;
}
const originHeader = request.headers.get("Origin");
// NOTE: You may need to use `X-Forwarded-Host` instead
const hostHeader = request.headers.get("Host");
if (originHeader === null || hostHeader === null) {
return new NextResponse(null, {
status: 403
});
}
let origin: URL;
try {
origin = new URL(originHeader);
} catch {
return new NextResponse(null, {
status: 403
});
}
if (origin.host !== hostHeader) {
return new NextResponse(null, {
status: 403
});
}
return NextResponse.next();
}