-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
43 lines (36 loc) · 1.14 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { CsrfError, createCsrfProtect } from "@edge-csrf/nextjs";
import { env } from "./env";
// initalize csrf protection method
const csrfProtect = createCsrfProtect({
cookie: {
secure: env.mode === "production",
},
});
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
"/((?!api|_next/static|_next/image|favicon.ico).*)",
],
};
// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest) {
const requestHeaders = request.headers;
requestHeaders.set("x-derivative-url", request.nextUrl.toString());
const response = NextResponse.next({ headers: requestHeaders });
try {
await csrfProtect(request, response);
} catch (err) {
if (err instanceof CsrfError)
return new NextResponse("invalid csrf token", { status: 403 });
throw err;
}
return response;
}