Skip to content

Instantly share code, notes, and snippets.

@tostu
Last active January 15, 2023 18:24
Show Gist options
  • Select an option

  • Save tostu/f6ba00df9369c337a77518836f8ab99d to your computer and use it in GitHub Desktop.

Select an option

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)
//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