Using Next.js middleware as a reverse proxy

Last updated:

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

import { NextResponse } from 'next/server'
export function middleware(request) {
let url = request.nextUrl.clone()
const hostname = url.pathname.startsWith("/ingest/static/") ? '' : ''
const requestHeaders = new Headers(request.headers)
requestHeaders.set('host', hostname)
url.protocol = 'https'
url.hostname = hostname
url.port = 443
url.pathname = url.pathname.replace(/^\/ingest/, '');
return NextResponse.rewrite(url, {
headers: requestHeaders,
export const config = {
matcher: '/ingest/:path*',

Add the skipTrailingSlashRedirect option to your next.config.js file:

// next.config.js
const nextConfig = {
// This is required to support PostHog trailing slash API requests
skipTrailingSlashRedirect: true,
module.exports = nextConfig

Once done, configure the PostHog client to send requests via your rewrite.

posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
api_host: ""
ui_host: "" // or "" if your PostHog is hosted in Europe


Was this page useful?

Next article

Using Nuxt routeRules as a reverse proxy

Nuxt 3 uses Nitro under the hood, which provides the routeRules config that can be used to proxy requests from one route to another. To do this, add the following routeRules to your nuxt.config.ts file: Then configure the PostHog client to send requests via your new proxy:

Read next article