-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
56 lines (51 loc) · 1.56 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
46
47
48
49
50
51
52
53
54
55
56
import { NextResponse } from "next/server";
export const config = {
matcher: "/numia/:path*",
};
/**
* /numia/osmosis-rpc/block -> https://osmosis-rpc.numia.xyz/block
* /numia/osmosis-lcd/cosmos/base/tendermint/v1beta1/blocks/10704303 -> https://osmosis-lcd.numia.xyz/cosmos/base/tendermint/v1beta1/blocks/10704303
* /numia/osmosis/height -> https://osmosis.numia.xyz/height
*/
export async function middleware(request) {
try {
const apiKey = process.env[`NUMIA_API_KEY`];
if (!apiKey) {
return new NextResponse(
JSON.stringify({
error: "Environment is missing the NUMIA_API_KEY variable.",
}),
{ status: 401 }
);
}
const url = new URL(request.url);
const parts = url.pathname.replace("/numia/", "").split("/");
const [subdomain, ...restPath] = parts;
const nextUrl = new URL(
`https://${subdomain}.numia.xyz/${restPath.join("/")}`
);
nextUrl.search = url.search;
// console.log("->", nextUrl.toString());
const result = await fetch(nextUrl, {
method: request.method,
body: request.body,
headers: {
authorization: `Bearer ${apiKey}`,
...request.headers,
},
});
return new NextResponse(result.body, {
headers: result.headers,
status: result.status,
statusText: result.statusText,
});
} catch (error) {
return new NextResponse(
JSON.stringify({
error:
"The middleware was not able to load the data and got an error response from the server.",
}),
{ status: 500 }
);
}
}