Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-pro· GoogleHugging Face LMArena Human Preference 140K

how do I set a supabase auth session's ip address via the x-forwarded-for field?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with gpt-4.1-2025-04-14’s answer.
  1. User

    how do I set a supabase auth session's ip address via the x-forwarded-for field?

  2. Gemini Assistant

    Excellent question. This is a common and important scenario when you have a proxy, load balancer, or serverless function sitting between your user and the Supabase backend.

    The good news is that Supabase is designed to handle this automatically. You generally don't need to do any special configuration on the Supabase side if you are using the hosted platform.

    Here’s a breakdown of how it works and what to do in different scenarios.


    1. The Automatic Case (Hosted Supabase)

    When a user's request goes through a proxy (like Vercel, Netlify, Cloudflare, or your own load balancer), the proxy terminates the original connection and makes a new one to Supabase. From Supabase's perspective, the IP address of the request is the proxy's IP.

    To solve this, proxies add the X-Forwarded-For header, which contains the original client's IP address.

    Supabase's infrastructure (specifically its API gateway, Kong) is pre-configured to:

    1. Look for the X-Forwarded-For header.
    2. Trust the IP addresses from known cloud providers (like Vercel, Cloudflare, etc.).
    3. Use the IP address from this header as the "real" client IP.

    This real IP is then passed to the authentication service (GoTrue), which records it in the auth.sessions table when a user signs in or refreshes their session.

    In summary: If you are using a standard hosting provider like Vercel, Netlify, or have Cloudflare in front of your app, it should just work. The proxy adds the header, and Supabase reads it.


    2. The Manual Case: Calling Supabase from Your Own Backend Server

    This is the scenario where you might need to take action. If you are making authentication calls to Supabase from your own server-side code (e.g., a Next.js API route, an Express server), your server acts as the proxy.

    In this case, you must manually forward the header from the incoming request to your server to the outgoing request to Supabase.

    Example: Next.js API Route

    Let's say you have an API route /api/login that handles user login.

    // pages/api/login.js
    import { createClient } from '@supabase/supabase-js';
    import { get } from 'http';
    
    export default async function handler(req, res) {
      if (req.method !== 'POST') {
        return res.status(405).json({ error: 'Method not allowed' });
      }
    
      // 1. Get the X-Forwarded-For header from the incoming request.
      // Vercel and other platforms populate this header automatically.
      const xForwardedFor = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
    
      // It can be a comma-separated list, so we take the first IP.
      const clientIp = Array.isArray(xForwardedFor)
        ? xForwardedFor[0]
        : xForwardedFor.split(',')[0].trim();
    
      // 2. Create a Supabase client configured to pass this header.
      const supabase = createClient(
        process.env.NEXT_PUBLIC_SUPABASE_URL,
        process.env.SUPABASE_SERVICE_ROLE_KEY, // Use service key for server-side
        {
          global: {
            headers: {
              // This is the crucial part
              'X-Forwarded-For': clientIp,
            },
          },
          auth: {
            // Important for server-side auth to not persist sessions
            persistSession: false
          }
        }
      );
    
      // 3. Perform the authentication call
      const { email, password } = req.body;
      const { data, error } = await supabase.auth.signInWithPassword({
        email,
        password,
      });
    
      if (error) {
        return res.status(error.status || 500).json({ message: error.message });
      }
    
      // Supabase has now recorded the session with the user's real IP
      return res.status(200).json(data);
    }
    

    Key steps in the code:

    1. Extract the IP: Read the x-forwarded-for header from the incoming request to your API route.
    2. Configure the Client: When creating the server-side Supabase client, use the global.headers option to set the X-Forwarded-For header on all outgoing requests from this client instance.
    3. Make the Call: Any auth calls made with this client instance (supabase.auth.signInWithPassword, signUp, etc.) will now include the correct header, and Supabase will log the user's real IP.

    3. The Self-Hosted Supabase Case

    If you are self-hosting Supabase using Docker, you are responsible for the proxy layer in front of it (e.g., Nginx, Traefik, Caddy).

    You need to ensure two things:

    1. Your proxy sets the header correctly.
    2. The Supabase Kong container is configured to trust your proxy.

    Example: Nginx Configuration

    In your Nginx server block that proxies requests to Supabase, make sure you have these lines:

    server {
        listen 443 ssl;
        server_name your-supabase-instance.com;
    
        # ... your SSL config ...
    
        location / {
            proxy_pass http://supabase_kong_upstream; # Your upstream to Kong
    
            # These headers are essential for forwarding client info
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
    

    The key line is proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;.

    In a self-hosted environment, Supabase's Kong gateway needs to be told which proxy IPs are "trusted". You can configure this via environment variables in your docker-compose.yml or Kubernetes configuration for the kong service. The relevant variable is KONG_TRUSTED_IPS.

    For example, if your Nginx proxy is running at IP 10.0.0.5, you would set: KONG_TRUSTED_IPS=10.0.0.5,::1


    How to Verify It's Working

    You can check the IP address recorded for a user's session in two ways:

    1. Supabase Dashboard:

      • Go to Authentication -> Users.
      • Click on a specific user.
      • Go to the Sessions tab.
      • The Last IP Address column will show the IP recorded for that session. It should be the user's IP, not your server's or proxy's.
    2. SQL Query:

      • Go to the SQL Editor in the Supabase dashboard.
      • Run a query against the auth.sessions table.
      select
        id,
        user_id,
        ip_address,
        created_at,
        updated_at
      from
        auth.sessions
      order by
        updated_at desc
      limit 10;
      

      The ip_address column should contain the end-user's IP.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.