Last active
January 15, 2023 18:24
-
-
Save tostu/f6ba00df9369c337a77518836f8ab99d to your computer and use it in GitHub Desktop.
Middleware to route single page requests with additional api key and mask origin address on edge hosting(vercel, cloudflare pages)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //currently not working with cloudflare pages due to a bug | |
| import type { NextRequest } from 'next/server' | |
| export default async function handler(req: NextRequest) { | |
| const { searchParams } = new URL(req.url) | |
| const route = searchParams.getAll('route').join('/') | |
| if (req.method === "GET"){ | |
| console.log(process.env.REST_API_URL) | |
| return fetch(`${process.env.REST_API_URL}${route}`, { | |
| redirect: 'manual', | |
| }) | |
| .catch((error) => { | |
| return new Response(error, { status: 503 }); | |
| }); | |
| } | |
| if (req.method !== "GET"){ | |
| try { | |
| const json = await req.json(); | |
| return fetch(`${process.env.REST_API_URL}${route}`, { | |
| method: req.method, | |
| headers: { | |
| 'Content-Type': 'application/json' | |
| }, | |
| body: JSON.stringify(json), | |
| redirect: 'manual', | |
| }) | |
| .catch((error) => { | |
| return new Response(error, { status: 503 }); | |
| }); | |
| } catch (e) { | |
| console.log(e); | |
| return new Response(null, { status: 400, statusText: "Bad Request" }); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment