Black Sheep Code
rss_feed

How to configure NextJS to proxy its requests

Published:

I found myself in a situation where I wanted to record the requests my NextJS application was making. Where for a straight client-side SPA I could use the network tab of the developer dev tools:

Screenshot indicating the HAR download button in Chrome's devtools

For an application that involves SSR and RSCs, it's not quite this simple - as some of those requests may be made on the server side - and be simply returning the rendered HTML to the browser.

The solution I've opted to investigate is using the tool mitmproxy, we proxy our requests through mitmproxy and and use that to record a HAR file.

Sample application

I have a sample application set up at this repository here, I'm request data in various forms from the jsonplaceholder API.

I have four kinds of requests:

Straight client side requests

This is the most basic, and this doesn't require special NextJS configuration - the request to jsonplaceholder is made directly from the browser, and if our browser is configured to use a proxy those requests will indeed be proxied.

Client side requests with rewrites

In this scenario we request the data via a relative path, and we configure NextJS to rewrite the request in the next.config.js file:

In this case the requests won't be directed to our proxy, as our browser proxy configuration doesn't proxy the localhost requests.

Server side requests - with native fetch

In this scenario the request is made on the server as a RSC. We need a way to instruct our application to proxy these requests via our proxy.

Server side requests - with node-fetch

This is the same scenario but we're using node-fetch instead of native fetch.

Solution - use a secondary proxy

The best solution I've found is to add your own secondary proxy, and have it proxy its traffic through your target proxy.

Create a proxy server with this script:

Update your requests, whether they're are server side requests or rewrites to reference an environment variable as the upstream.

Start both your secondary proxy and NextJS application with the NODE_EXTRA_CA_CERTS env var provided.

Here you can see mitmproxy recording my requests!

Screenshot of mitmproxy in action

Alternative solutions

If the secondary proxy approach doesn't work for you, you can configure the proxying of your http client (eg. fetch or node-fetch) directly. See my post here for details.



Questions? Comments? Criticisms? Get in the comments! 👇

Spotted an error? Edit this page with Github