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:

// next.config.js
const nextConfig = {
async rewrites() {
return [
source: "/ingest/:path*",
destination: "*",
module.exports = nextConfig

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

posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
api_host: ""

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


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 or . 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 by checking the network tab on your domain.

Read next article