-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.js
36 lines (30 loc) · 906 Bytes
/
middleware.js
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
// eslint-disable @next/next/no-server-import-in-page
import { NextResponse } from 'next/server';
import * as R from 'ramda';
import cors from './utils/cors';
import {
getTokenFromAuthorizationHeaderValue,
verifyToken,
} from './utils/authUtil';
export const middleware = async (req) => {
if (req.method === 'OPTIONS') {
return cors(req, new NextResponse(null, { status: 200 }));
}
if (!R.startsWith('/api/backend', req.nextUrl.pathname)) {
// not protected apis; continue
return cors(req, NextResponse.next());
}
// protected apis; check auth
const token = getTokenFromAuthorizationHeaderValue(
req.headers.get('Authorization'),
);
try {
await verifyToken(token);
return cors(req, NextResponse.next());
} catch (e) {
return cors(req, new NextResponse('Auth required', { status: 401 }));
}
};
export const config = {
matcher: ['/api/:path*'],
};