how do I set a supabase auth session's ip address via the x-forwarded-for field?
- User
how do I set a supabase auth session's ip address via the x-forwarded-for field?
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-Forheader, which contains the original client's IP address.Supabase's infrastructure (specifically its API gateway, Kong) is pre-configured to:
- Look for the
X-Forwarded-Forheader. - Trust the IP addresses from known cloud providers (like Vercel, Cloudflare, etc.).
- 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.sessionstable 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/loginthat 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:
- Extract the IP: Read the
x-forwarded-forheader from the incoming request to your API route. - Configure the Client: When creating the server-side Supabase client, use the
global.headersoption to set theX-Forwarded-Forheader on all outgoing requests from this client instance. - 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:
- Your proxy sets the header correctly.
- The Supabase Kong container is configured to trust your proxy.
Example: Nginx Configuration
In your Nginx
serverblock 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.ymlor Kubernetes configuration for thekongservice. The relevant variable isKONG_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:
-
Supabase Dashboard:
- Go to Authentication -> Users.
- Click on a specific user.
- Go to the Sessions tab.
- The
Last IP Addresscolumn will show the IP recorded for that session. It should be the user's IP, not your server's or proxy's.
-
SQL Query:
- Go to the SQL Editor in the Supabase dashboard.
- Run a query against the
auth.sessionstable.
select id, user_id, ip_address, created_at, updated_at from auth.sessions order by updated_at desc limit 10;The
ip_addresscolumn should contain the end-user's IP.
- Look for the
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.