Skip to content

Next.js Proxy

Route usertrax analytics through your Next.js application using built-in rewrites.

  1. Add rewrites to next.config.js

    Create or update next.config.js in your project root:

    /** @type {import('next').NextConfig} */
    const nextConfig = {
    async rewrites() {
    return [
    {
    source: "/cvs.js",
    destination: "https://usertrax.io/cvs.js",
    },
    {
    source: "/api/usertrax/events",
    destination: "https://api.usertrax.io/api/events",
    },
    ];
    },
    };
    module.exports = nextConfig;

    Next.js automatically forwards the request body and headers, including X-Auth-Key.

    If you already use /api/usertrax/events for your own API, pick a different path (e.g. /api/ut/events) and set the same path in usertraxConfig.endpoint.

  2. Update your script tag

    App Router — in app/layout.tsx:

    export default function RootLayout({ children }: { children: React.ReactNode }) {
    return (
    <html lang="en">
    <head>
    <script
    dangerouslySetInnerHTML={{
    __html: `window.usertraxConfig = { endpoint: "/api/usertrax/events" };`,
    }}
    />
    <script
    src="/cvs.js"
    data-key={process.env.NEXT_PUBLIC_USERTRAX_KEY}
    defer
    />
    </head>
    <body>{children}</body>
    </html>
    );
    }

    Pages Router — in pages/_document.tsx:

    import { Html, Head, Main, NextScript } from "next/document";
    export default function Document() {
    return (
    <Html lang="en">
    <Head>
    <script
    dangerouslySetInnerHTML={{
    __html: `window.usertraxConfig = { endpoint: "/api/usertrax/events" };`,
    }}
    />
    <script
    src="/cvs.js"
    data-key={process.env.NEXT_PUBLIC_USERTRAX_KEY}
    defer
    />
    </Head>
    <body>
    <Main />
    <NextScript />
    </body>
    </Html>
    );
    }
  3. Deploy

    Rewrites take effect automatically after deployment on Vercel, Netlify, and other Next.js hosts.

  1. Visit your website
  2. Open the Network tab in DevTools
  3. Confirm cvs.js and event POSTs use your domain, not usertrax.io or api.usertrax.io
  • 401 errors: Verify data-key is set and rewrites are active (check response headers — proxied requests should reach usertrax)
  • Rewrites not working locally: Restart the dev server after changing next.config.js