Search code examples
ip-addresssveltekitpublic

How to add a user's public IP to the X-Forwarded-For header using SvelteKit and TypeScript?


I'm developing a web application with SvelteKit and TypeScript. During the login process, I aim to send the logged-in user's public IP information in the headers.

event.locals.clientIP = event.getClientAddress();

event.getClientAddress() just return local ip.

How can I correctly add the logged-in user's public IP to the X-Forwarded-For header?

Additional Info:

I'd prefer not to use external APIs to fetch the public IP due to potential security vulnerabilities. Is there an alternative method to obtain the IP?


Solution

  • It's possible to get the client IP on server side:

    +page.server.ts:

    /** @type {import('@sveltejs/kit').RequestHandler} */
    export async function load(event) {
        return { ip: event.getClientAddress() };
    }
    

    And access it on client side:

    +page.svelte:

    <script lang="ts">
        import type { PageData } from './$types';
        export let data: PageData;
    </script>
    
    {#if data?.ip}
        <p>ip to test: {data.ip}</p>
    {/if}
    

    Note that when running on localhost, you'll get your local IP, but after deploying to production, then the user IP will be returned.