Skip to content

Instantly share code, notes, and snippets.

@simonhaenisch
Last active May 27, 2024 23:22
Show Gist options
  • Save simonhaenisch/7ffcd9833ddaf4236e036d33d018dd2f to your computer and use it in GitHub Desktop.
Save simonhaenisch/7ffcd9833ddaf4236e036d33d018dd2f to your computer and use it in GitHub Desktop.
How to intercept node-fetch (Next.js) requests so that headers can be inspected (with Proxyman).
  1. Install Proxyman (https://proxyman.io/).
  2. Install https-proxy-agent from NPM (https://www.npmjs.com/package/https-proxy-agent).
  3. Add an agent to your fetch call so that requests get sent through Proxyman.
import ProxyAgent from 'https-proxy-agent';

export const request = async (url: string, options: RequestOptions) => fetch(url, {
  ...options,
  agent: ProxyAgent('http://localhost:9090'), // 9090 is the default port of Proxyman (see prefs)
} as any);
  1. Add the following to your next.config.js so that https-proxy-agent doesn't complain about missing modules.
module.exports = {
  webpack: (config, { isServer }) =>
    isServer ? config : { ...config, node: { net: 'empty', tls: 'empty' } },
};
  1. If you're making HTTPS requests, you'll have to enable SSL proxying for the app (node) or domain in Proxyman so you can inspect the requests. In that case you'll run into an error UNABLE_TO_VERIFY_LEAF_SIGNATURE. You can get around this by temporarily disabling certificate verification. To do so, simply run your app like NODE_TLS_REJECT_UNAUTHORIZED=0 npm start (see https://stackoverflow.com/a/20100521/2897426).

The agent field is not officially part of the fetch API but because Next.js uses node-fetch under the hood, it actually works. That's why the request init is casted with as any.

@tonyxiao
Copy link

Could this work with the automatic setup of proxyman/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment