Using Next.js rewrites as a reverse proxy

Last updated:

|Edit this page

On this page

Note: If you are using the EU cloud then use eu instead of us in all domains (e.g. ->

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:

// next.config.js
const nextConfig = {
async rewrites() {
return [
source: "/ingest/static/:path*",
destination: "*",
source: "/ingest/:path*",
destination: "*",
// 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.

posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
api_host: "/ingest",
ui_host: '<ph_app_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 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 router , 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. Add the skipTrailingSlashRedirect option to your next.config.js file: Once done, configure…

Read next article