Using Next.js rewrites as a reverse proxy

Last updated:

|Edit this page

On this page

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 to your next.config.js file:

JavaScript
// next.config.js
const nextConfig = {
async rewrites() {
return [
{
source: "/ingest/:path*",
destination: "https://app.posthog.com/:path*",
},
];
},
}
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: "https://your-host.com/ingest"
})

If this isn't working for you (returning 503 errors), it may be an issue with how your hosting service (such as Heroku) handles rewrites. You can write Next.js middleware to proxy requests instead.

Setup video

Questions?

Was this page useful?

Next article

Using Netlify redirects as a reverse proxy

Netlify supports redirects and rewrites which we can use as a reverse proxy from an /ingest route to https://app.posthog.com or https://eu.posthog.com . In your netlify.toml file, add a redirect like this: Once done, set the /ingest route of your domain as the API host in your PostHog initialization like this: Once updated, deploy your changes on Netlify and check that PostHog requests are going to https://www.your-domain.com/ingest by checking the network tab on your domain.

Read next article