Next.js Proxy
Route usertrax analytics through your Next.js application using built-in rewrites.
Add rewrites to
next.config.jsCreate or update
next.config.jsin 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/eventsfor your own API, pick a different path (e.g./api/ut/events) and set the same path inusertraxConfig.endpoint.Update your script tag
App Router — in
app/layout.tsx:export default function RootLayout({ children }: { children: React.ReactNode }) {return (<html lang="en"><head><scriptdangerouslySetInnerHTML={{__html: `window.usertraxConfig = { endpoint: "/api/usertrax/events" };`,}}/><scriptsrc="/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><scriptdangerouslySetInnerHTML={{__html: `window.usertraxConfig = { endpoint: "/api/usertrax/events" };`,}}/><scriptsrc="/cvs.js"data-key={process.env.NEXT_PUBLIC_USERTRAX_KEY}defer/></Head><body><Main /><NextScript /></body></Html>);}Deploy
Rewrites take effect automatically after deployment on Vercel, Netlify, and other Next.js hosts.
Verification
Section titled “Verification”- Visit your website
- Open the Network tab in DevTools
- Confirm
cvs.jsand event POSTs use your domain, notusertrax.ioorapi.usertrax.io
Troubleshooting
Section titled “Troubleshooting”- 401 errors: Verify
data-keyis 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