How to use same origin through Vercel
Updated Mar 28, 2025
This instruction uses /metrics as an example of the same origin path. You can use any of your own.
You should also use the URL of your sGTM container instead of https://sgtm.example.com.
Step 1. Create a Serverless Function
In your project, create a file under API/ (for example, api/metrics.js):
// api/metrics.js
// The external URL you want to proxy to:
const TARGET_URL = "https://sgtm.example.com";
module.exports = async (req, res) => {
// Vercel populates x-forwarded-for with the real client IP (among others).
// The first IP is typically the visitor’s IP.
const forwardedFor = req.headers["x-forwarded-for"] || "";
const clientIp = forwardedFor.split(",")[0].trim() || "unknown";
// Build new headers for forwarding
const newHeaders = {
// Spread original request headers if you want
...req.headers,
// Override or add your custom ones
"X-Forwarded-For": clientIp,
"X-From-Cdn": "cf-stape",
"Host": "sgtm.example.com",
"CF-Connecting-Ip": clientIp
};
// Forward the request to the target
// NOTE: If you need the original body, you can pass it along.
// But in Node serverless on Vercel, `req` is a stream, so you’d typically
// parse it first (e.g. using `req.body` if using Next.js API routes).
const response = await fetch(TARGET_URL, {
method: req.method,
headers: newHeaders,
// If you need the original POST body, see note below
body: req
});
// Relay the response back to the client
const text = await response.text();
// Copy headers from the upstream response
for (const [key, value] of response.headers.entries()) {
res.setHeader(key, value);
}
res.status(response.status).send(text);
};
Step 2. Deploy the changes and test it
You can verify the proxy is working by opening your proxy path in the browser. Go to https://sgtm.example.com/metrics. If you see error 400, everything works correctly. You can also preview the server container by accessing the /metrics path.
After following these steps, add your /path for the same origin to the Custom Loader's settings. Check the article on Same Origin Path to do this.
🍽️ Table of content:
no spam!
Subscribe to product updates:
Can’t find what you are looking for?