Docs·Proxy guide
Proxy with Nuxt
One server route serves Spreelytics from /sp/. This guide uses /sp/. Any path works if nothing else on your site uses it and it doesn't contain words like "analytics" or "tracking", which blockers look for.
Add the server route
Create server/routes/sp/[...path].ts:
// server/routes/sp/[...path].ts
// Serves Spreelytics from /sp/ on your site: /sp/js/ is the script, everything else is tracking.
const SCRIPTS = "https://cdn.spreelytics.com/cdn/sdk/";
const API = "https://sdk.spreelytics.com/1.0/";
const FORWARD = ["content-type", "user-agent", "origin", "referer", "accept", "accept-language"];
export default defineEventHandler(async (event) => {
const path = getRouterParam(event, "path") ?? "";
const target = (path.startsWith("js/") ? SCRIPTS + path.slice(3) : API + path) + getRequestURL(event).search;
const headers = new Headers();
for (const name of FORWARD) {
const value = getRequestHeader(event, name);
if (value) headers.set(name, value);
}
// The visitor's IP address, from X-Forwarded-For when your host sets it.
const ip = getRequestIP(event, { xForwardedFor: true })?.split(",")[0].trim();
if (ip) headers.set("x-forwarded-for", ip);
const method = event.method;
const upstream = await fetch(target, {
method,
headers,
body: method === "GET" || method === "HEAD" ? undefined : await readRawBody(event, false),
});
// fetch has already unzipped the body, so these headers no longer apply.
const responseHeaders = new Headers(upstream.headers);
responseHeaders.delete("content-encoding");
responseHeaders.delete("content-length");
return new Response(upstream.body, { status: upstream.status, headers: responseHeaders });
});
Point the script at your proxy
In your Spreelytics snippet (see Nuxt), load the script through /sp/js/ and add api_host:
<script src="/sp/js/spreelytics-loader.js"></script>
<script>
Spreelytics.init({
client_key: "YOUR_CLIENT_KEY",
api_host: "https://www.example.com/sp",
});
</script>
Check it works
Open your site with the browser's Network tab open and filtered by /sp/. The script files and
requests like track/page should come from your own domain, with status 200. In Spreelytics,
Settings → Tracking script says "Last seen just now" and Realtime shows you in your own country.
- Wrong country, or
200and nothing arrives: the proxy isn't passing the visitor's IP address inX-Forwarded-For. See The visitor's IP address below. 401: theOriginandRefererheaders didn't arrive, or your domain isn't in Allowed domains.
The visitor's IP address
getRequestIP reads X-Forwarded-For when your host sets it, and the connection's address otherwise.
Related
- Proxy overview: the other ways to set it up.
- Filter traffic: which traffic Spreelytics drops.