-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
36 lines (32 loc) · 1.03 KB
/
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
import { next } from '@vercel/edge';
const fetchApi = async (req) => {
const baseUrl = 'https://opendata.resas-portal.go.jp';
const [path] = req.url.match(/\/api\/v1\/(.*)/);
const response = await fetch(`${baseUrl}/${path}`, {
headers: { 'X-API-KEY': process.env.VERCEL_API_KEY },
}).then((res) => res.blob());
return new Response(response);
};
export default async (req) => {
// Basic Auth
const authorizationHeader = req.headers.get('authorization');
if (authorizationHeader) {
const basicAuth = authorizationHeader.split(' ')[1];
const [user, password] = atob(basicAuth).toString().split(':');
if (user === process.env.BASIC_AUTH_USER && password === process.env.BASIC_AUTH_PASSWORD) {
if (req.url.includes('/api')) {
return fetchApi(req);
}
return next();
}
}
return new Response('Basic Auth required', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Secure Area"',
},
});
};
export const config = {
matcher: ['/(.*)', '/', '/index.html'],
};