1

I know that we can access user's IP address in Astro using Astro.clientAddress value but this would only work in .astro pages.

// your-ip.astro

---
const detectedIp = Astro.clientAddress;
---

<h1>
Your IP: {{ detectedIP }}
</h1>

but in my case, I have created a server-side API endpoint in Astro itself so like below.

// pages/api/create-user.ts

export async function post({ request }) {
    console.log(await request.json());


    // I want to do like this in typescript endpoint file
    // const IP = Astro.clientAddress;


    return {
        body: JSON.stringify({
            name: 'Astro',
            url: 'https://astro.build/',
            ip: `Your IP: {IP}`
        }),
    };
}

I want to access the user's IP address within this typescript file itself, but I think Astro is not provided in the .ts file context. So how to achieve that?

I looked at documentation around it but couldn't find out how to access that.

Visrut
  • 360
  • 4
  • 14

1 Answers1

1

You can access the clientAddress from the API context object in an endpoint function.

import type { APIContext } from 'astro';

export function get({ clientAddress }: APIContext) {
  return {
    body: `Your IP address is: ${clientAddress}`
  }
}
The Otterlord
  • 1,680
  • 10
  • 20