Skip to content

Astro Proxy

Route usertrax through your Astro application. Choose middleware (SSR) or API routes (static/hybrid).

  1. Enable server output

    astro.config.mjs
    import { defineConfig } from "astro/config";
    import node from "@astrojs/node";
    export default defineConfig({
    output: "server",
    adapter: node({ mode: "standalone" }),
    });

    Install the adapter: npm install @astrojs/node

  2. Create middleware

    src/middleware.js
    const UPSTREAM_SCRIPT = "https://usertrax.io/cvs.js";
    const UPSTREAM_EVENTS = "https://api.usertrax.io/api/events";
    export async function onRequest(context, next) {
    const { request } = context;
    const url = new URL(request.url);
    if (url.pathname === "/cvs.js") {
    const response = await fetch(UPSTREAM_SCRIPT);
    const script = await response.text();
    return new Response(script, {
    headers: {
    "Content-Type": "application/javascript",
    "Cache-Control": "public, max-age=86400",
    },
    });
    }
    if (url.pathname === "/api/usertrax/events" && request.method === "POST") {
    const body = await request.text();
    const response = await fetch(UPSTREAM_EVENTS, {
    method: "POST",
    headers: {
    "Content-Type": request.headers.get("Content-Type") || "application/json",
    Accept: "application/json",
    "User-Agent": request.headers.get("User-Agent") || "",
    "X-Auth-Key": request.headers.get("X-Auth-Key") || "",
    },
    body,
    });
    return new Response(await response.text(), {
    status: response.status,
    headers: { "Content-Type": "application/json" },
    });
    }
    return next();
    }
  3. Update your layout

    src/layouts/Layout.astro
    ---
    const { title } = Astro.props;
    ---
    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>{title}</title>
    <script is:inline>
    window.usertraxConfig = { endpoint: "/api/usertrax/events" };
    </script>
    <script src="/cvs.js" data-key="YOUR_API_KEY" defer></script>
    </head>
    <body>
    <slot />
    </body>
    </html>
  1. Visit your website
  2. Open the Network tab
  3. Confirm requests go through your domain
  • Middleware not running: Ensure output: "server" or output: "hybrid" is set
  • 404 on API routes: Check file naming — Astro uses src/pages/api/usertrax/events.js for the /api/usertrax/events route