Real Client IP with @sentry/nextjs tunnel?

Looks like I found a workaround. Adding forwarded_for: "<real-ip>" into the envelope header results in Sentry UI displaying the correct client IP.

I would appreciate it if any Sentry folks could offer a less hacky way to do this or confirm that this is indeed the intended way to do it.

Here’s roughly what my code looks like for that:

    const envelope = req.body;
    const [rawHeader, ...restPieces] = envelope.split('\n');

    const header = JSON.parse(rawHeader);

    // omitted: check DSN, host, project ID

    const body = [
      // HACK: Attempt to communicate the real client IP address to Sentry.
      //       The `forwarded_for` field was deduced from a test in Sentry's
      //       Relay (server) handling of the Envelope format,
      //       cf. https://git.io/JPwWP
      JSON.stringify({
        ...header,
        forwarded_for:
          typeof req.headers['x-forwarded-for'] === 'string'
            ? req.headers['x-forwarded-for']
            : req.socket.remoteAddress,
      }),
      ...restPieces,
    ].join('\n');

    const url = `https://${sentryHost}/api/${projectId}/envelope/`;
    const response = await fetch(url, {
      method: 'POST',
      body,
    });

The existence of this field was deduced from a Relay test here: relay/envelope.rs at 2e924639d7bcfa24db69ba2ed78a82e2c07478e1 · getsentry/relay · GitHub

1 Like