Next.js Proxy

Set up an EngageTrack proxy with Next.js middleware or rewrites.

Next.js Proxy

There are two ways to proxy EngageTrack through a Next.js application: rewrites (simplest) or middleware (more control).

Add rewrites to your next.config.js (or next.config.ts):

/** @type {import('next').NextConfig} */
const nextConfig = {
	async rewrites() {
		return [
			{
				source: "/js/script.js",
				destination: "https://cdn.engagetrack.net/sdk.js",
			},
			{
				source: "/api/event",
				destination: "https://api.engagetrack.net/api/v1/event",
			},
		];
	},
};
 
module.exports = nextConfig;

Then update your script tag:

<script
	defer
	data-site-id="YOUR_SITE_ID"
	data-api="/api/event"
	src="/js/script.js"
></script>

Next.js rewrites automatically forward the client's IP address and headers, so geolocation works out of the box.

Next.js App Router Component

If you use the App Router, create a component to load the script:

// components/engagetrack.tsx
export function EngageTrack() {
	return (
		<script
			defer
			data-site-id="YOUR_SITE_ID"
			data-api="/api/event"
			src="/js/script.js"
		/>
	);
}

Add it to your root layout:

// app/layout.tsx
import { EngageTrack } from "@/components/engagetrack";
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
	return (
		<html lang="en">
			<head>
				<EngageTrack />
			</head>
			<body>{children}</body>
		</html>
	);
}

Option 2: Middleware

For more control (e.g., adding custom headers, rate limiting), use Next.js middleware:

// middleware.ts
import { NextRequest, NextResponse } from "next/server";
 
export function middleware(request: NextRequest) {
	const url = request.nextUrl.pathname;
 
	if (url === "/js/script.js") {
		return NextResponse.rewrite(
			new URL("https://cdn.engagetrack.net/sdk.js")
		);
	}
 
	if (url === "/api/event") {
		const destination = new URL("https://api.engagetrack.net/api/v1/event");
		const response = NextResponse.rewrite(destination);
 
		// Forward the client IP for geolocation
		const ip = request.headers.get("x-forwarded-for") || request.ip;
		if (ip) {
			response.headers.set("X-Forwarded-For", ip);
		}
 
		return response;
	}
 
	return NextResponse.next();
}
 
export const config = {
	matcher: ["/js/script.js", "/api/event"],
};

If you already have middleware in your project, merge the EngageTrack routes into your existing middleware function rather than creating a separate file. Next.js only supports a single middleware.ts.

Verify the Proxy

  1. Open your site and check that the script loads from your domain (Network tab in DevTools)
  2. Add data-debug="true" to the script tag
  3. Open the console and confirm events are being sent to /api/event (your proxy) instead of api.engagetrack.net
  4. Check the EngageTrack dashboard — pageviews should appear within a few seconds