Using Next.js rewrites as a reverse proxy

Warning
  1. The following self-hosted proxy isn't provided by PostHog, so we can't take responsibility for it! If unsure, we recommend using our managed reverse proxy.

  2. If you are using the EU cloud then use eu instead of us in all domains (e.g. us.i.posthog.com -> eu.i.posthog.com).

  3. Avoid using generic or common path names like /analytics, /tracking, /ingest, or /posthog for your reverse proxy. They will most likely be blocked. Instead, use a non-obvious path name or something random and unique to your application that's unlikely to appear in a filter list.

If you are using Next.js, you can take advantage of rewrites to behave like a reverse proxy. To do so, add a rewrites() function and the skipTrailingSlashRedirect option to your next.config.js file:

JavaScript
// next.config.js
const nextConfig = {
async rewrites() {
return [
{
source: "/<ph_proxy_path>/static/:path*",
destination: "https://us-assets.i.posthog.com/static/:path*",
},
{
source: "/<ph_proxy_path>/:path*",
destination: "https://us.i.posthog.com/:path*",
},
];
},
// This is required to support PostHog trailing slash API requests
skipTrailingSlashRedirect: true,
}
module.exports = nextConfig

Then configure the PostHog client to send requests via your rewrite.

JavaScript
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
api_host: "/<ph_proxy_path>",
ui_host: '<ph_app_host>'
})

If this isn't working for you (returning 503 or 400 errors), it may be an issue with how your hosting service (such as Heroku or Netlify) handles rewrites. You can write Next.js middleware or use a host-specific proxy (like Netlify) instead. For example, Netlify modifies the Content-Encoding header when using rewrites(), which causes PostHog to fail to parse the request. This doesn't happen if you use their _redirects file or netlify.toml options.

Setup video

Community questions

Was this page useful?

Questions about this page? or post a community question.