I'm making a GET request to a Vercel edge function but can't seem to get IP Address inside API function.
all these headers values are showing undefined
export const config = {
runtime: "edge",
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<APIResponseData>
) {
console.log("realip", req.headers["x-real-ip"]);
console.log("forwardedfor", req.headers["x-forwarded-for"]);
console.log("vercelforwardedfor", req.headers["x-vercel-forwarded-for"]);
console.log("x-vercel-ip-country", req.headers["x-vercel-ip-country"]);
return new Response(
JSON.stringify({
data: {
data: "ok",
},
}),
{
status: 200,
headers: {
"content-type": "application/json"
},
}
);
}
This worked:
edge function:
import { ipAddress } from "@vercel/edge";
export const config = {
runtime: "edge",
};
export default function (request: Request) {
const ip = ipAddress(request) || "unknown";
return;
new Response(
`<h1>Your IP is
${ip}
</h1>`,
{
headers: {
"content-type": "text/html",
},
}
);
}
edge middleware:
import { ipAddress } from "@vercel/edge";
export const config = {
runtime: "edge",
};
export default function (request: Request) {
const ip = ipAddress(request) || "unknown";
return;
new Response(
`<h1>Your IP is
${ip}
</h1>`,
{
headers: {
"content-type": "text/html",
},
}
);
}
ref: https://vercel.com/docs/concepts/functions/edge-functions/vercel-edge-package#ipaddress