File size: 1,235 Bytes
ccc21f3 | 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 | import { createProxyMiddleware } from "http-proxy-middleware";
import type { RequestHandler } from "express";
const CLERK_FAPI = "https://frontend-api.clerk.dev";
export const CLERK_PROXY_PATH = "/api/__clerk";
export function clerkProxyMiddleware(): RequestHandler {
if (process.env.NODE_ENV !== "production") {
return (_req, _res, next) => next();
}
const secretKey = process.env.CLERK_SECRET_KEY;
if (!secretKey) {
return (_req, _res, next) => next();
}
return createProxyMiddleware({
target: CLERK_FAPI,
changeOrigin: true,
pathRewrite: (path) => path.replace(new RegExp("^" + CLERK_PROXY_PATH), ""),
on: {
proxyReq: (proxyReq, req) => {
const protocol = req.headers["x-forwarded-proto"] || "https";
const host = req.headers.host || "";
proxyReq.setHeader("Clerk-Proxy-Url", protocol + "://" + host + CLERK_PROXY_PATH);
proxyReq.setHeader("Clerk-Secret-Key", secretKey);
const xff = req.headers["x-forwarded-for"];
const clientIp = (Array.isArray(xff) ? xff[0] : xff)?.split(",")[0]?.trim() || req.socket?.remoteAddress || "";
if (clientIp) proxyReq.setHeader("X-Forwarded-For", clientIp);
},
},
}) as RequestHandler;
} |