Vercel
Routing Middleware serves the script from your domain, passes its counts on, and names the visitor from what Vercel knows of them.
Add Routing Middleware, a middleware.js at the root of your project, which names the visitor
from what Vercel knows of them. Install @vercel/functions for it:
import { geolocation, ipAddress, rewrite } from '@vercel/functions';
export const config = { matcher: ['/js/tally.js', '/api/tally'] };
export default function middleware(request) {
const { pathname } = new URL(request.url);
const headers = new Headers(request.headers);
headers.delete('cookie');
headers.delete('authorization');
const place = geolocation(request);
const visitor = {
'X-Fivebar-IP': ipAddress(request),
'X-Fivebar-Country': place.country,
'X-Fivebar-City': place.city,
};
for (const [name, value] of Object.entries(visitor)) {
if (value) headers.set(name, encodeURIComponent(value));
}
return rewrite(new URL(pathname, 'https://fiveb.ar'), { request: { headers } });
}With Next.js, put the same in middleware.js (proxy.js from Next.js 16), returning
NextResponse.rewrite(url, { request: { headers } }) in place of rewrite(). Two rewrites
in vercel.json would proxy the paths too, but Vercel doesn’t say that they pass on where the
visitor is. If Cloudflare is in front of your Vercel site, Vercel sees Cloudflare rather than the visitor, so use
the Cloudflare recipe instead. See Vercel’s help on
Routing Middleware.
Hosted anywhere but Vercel, Next.js’s own rewrites() don’t pass on the visitor’s address, so
every visitor would count as one. Proxy with whatever is in front of it instead, such as nginx or
Caddy.
Load the script
Once the proxy is live, load the script from your own domain. It sends its counts to the host it was loaded from, so nothing else changes:
<script async data-domain="example.com" src="/js/tally.js"></script>Then check it works. If either path is already taken on your site, see Other paths. Proxying says how it works and which headers name the visitor.