Using Next.js rewrites as a reverse proxy

Last updated:

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 Next.js middleware as a reverse proxy

If you are using Next.js and rewrites aren't working for you , you can write custom middleware to proxy requests to PostHog. To do this using the app directory, create a file named middleware.js in your base directory (same level as the app folder). In this file, set up code to match requests to a custom route, set a new host header, change the URL to point to PostHog, and rewrite the response. Once done, configure the PostHog client to send requests via your rewrite.

Read next article