-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
44 lines (34 loc) · 994 Bytes
/
middleware.ts
File metadata and controls
44 lines (34 loc) · 994 Bytes
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
import { NextResponse } from 'next/server';
import { NextRequest } from 'next/server';
import type { Maybe } from "./lib/database/types"
export const config = {
matcher: [
'/api/:path*',
],
};
const apiAccessRefusedResponse = (errorMessage = 'access denied') => {
const payload: Maybe<unknown> = {
error: errorMessage
}
return new NextResponse(JSON.stringify(payload), { status: 403 })
}
function apiMiddleWare(request: NextRequest) {
const url = new URL(request.url);
const origin = request.headers.get('Origin')
if (request.method === 'GET') {
// GET is allowed
return NextResponse.next()
}
if (origin && origin === url.origin) {
// other methods must be from same origin
return NextResponse.next()
}
return apiAccessRefusedResponse()
}
export function middleware(request: NextRequest) {
const url = new URL(request.url);
if (url.pathname.startsWith('/api')) {
return apiMiddleWare(request)
}
return NextResponse.next();
}