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. us.i.posthog.com -> eu.i.posthog.com)

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: "/ingest/static/:path*",
destination: "https://us-assets.i.posthog.com/static/:path*",
},
{
source: "/ingest/: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: "/ingest",
ui_host: 'https://us.i.posthog.com' // or 'https://eu.i.posthog.com' if your PostHog is hosted in Europe
})

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 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