Created
December 6, 2024 06:42
-
-
Save theJian/59d43fa83a885c387455ff46a9de981a to your computer and use it in GitHub Desktop.
frontend api proxy
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
// /api/proxy/[...slug].ts | |
import httpProxy from "http-proxy"; | |
import { omitBy } from "lodash"; | |
import { NextApiRequest, NextApiResponse } from "next"; | |
export const config = { | |
api: { | |
bodyParser: false, | |
externalResolver: true, | |
}, | |
}; | |
const isDev = process.env.NODE_ENV === "development"; | |
const isCorsHeader = (header: string) => | |
header.toLowerCase().startsWith("access-control-"); | |
const getQueryString = (req: NextApiRequest) => { | |
const url = req.url; | |
if (!url) return ""; | |
const indexStart = url.indexOf("?"); | |
if (indexStart === -1) return ""; | |
return url.substring(indexStart); | |
}; | |
export default async (req: NextApiRequest, res: NextApiResponse<any>) => { | |
if (!isDev) { | |
res.status(400).end(); | |
return; | |
} | |
const proxyTarget = process.env.NEXT_PUBLIC_PROXY_TARGET; | |
if (!proxyTarget) { | |
res.status(500).send({ | |
error: | |
"environment variable `NEXT_PUBLIC_PROXY_TARGET` needs to be presented for api proxy to work", | |
}); | |
return; | |
} | |
const { slug = [] } = req.query; | |
const path = Array.isArray(slug) ? slug.join("/") : slug; | |
const queryString = getQueryString(req); | |
req.url = path + queryString; | |
httpProxy | |
.createProxy() | |
.on("proxyRes", (proxyRes, req, res) => { | |
// Prevent CORS headers from populating into response | |
proxyRes.headers = omitBy(proxyRes.headers, (_, header) => | |
isCorsHeader(header) | |
); | |
// Rewrite CORS header | |
if ("origin" in req.headers) { | |
res.setHeader("access-control-allow-origin", "*"); | |
res.setHeader("access-control-allow-credentials", "true"); | |
} | |
if (req.headers["access-control-request-method"]) { | |
res.setHeader( | |
"access-control-allow-methods", | |
req.headers["access-control-request-method"] | |
); | |
} | |
if (req.headers["access-control-request-headers"]) { | |
res.setHeader( | |
"access-control-allow-headers", | |
req.headers["access-control-request-headers"] | |
); | |
} | |
}) | |
.web(req, res, { | |
changeOrigin: true, | |
target: proxyTarget, | |
cookieDomainRewrite: "localhost", | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment