Using Next.js middleware as a reverse proxy

Last updated:

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.

JavaScript
import { NextResponse } from 'next/server'
export function middleware(request) {
const hostname = 'app.posthog.com' // or 'eu.posthog.com'
const requestHeaders = new Headers(request.headers)
requestHeaders.set('host', hostname)
let url = request.nextUrl.clone()
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*',
}

Once done, 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"
})

Questions?

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 https://app.posthog.com or https://eu.posthog.com . 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 https://www.your-domain.com/ingest by checking the network tab on your domain.

Read next article