link-stack/apps/link/metamigo-api/proxy/[[...path]]/route.js
Darren Clarke c620e4bf25 Flatten
2023-08-25 07:11:33 +00:00

33 lines
1 KiB
JavaScript

import { createProxyMiddleware } from "http-proxy-middleware";
const handler = createProxyMiddleware({
target:
process.env.NODE_ENV === "production"
? "http://metamigo-api:3001"
: "http://localhost:3001",
changeOrigin: true,
pathRewrite: { "^/api/v1": "/api" },
xfwd: true,
onProxyReq(proxyReq, req) {
const auth = proxyReq.getHeader("authorization");
if (auth) {
// pass along user provided authorization header
return;
}
// Else extract the session token from the cookie and pass
// as bearer token to the proxy target
// const token = req.cookies["next-auth.session-token"];
let token = req.cookies["__Secure-next-auth.session-token"];
if (!token) token = req.cookies["next-auth.session-token"];
if (token) {
proxyReq.setHeader("authorization", `Bearer ${token}`);
proxyReq.removeHeader("cookie");
} else {
console.error("no token found. proxied request to backend will fail.");
}
},
});
export { handler as GET, handler as POST, handler as PUT, handler as DELETE};