How to Get User's IP Address in NextJS
Jasser Mark Arioste
Hello, hustlers! In this tutorial, you’ll learn how to get the user’s IP address in NextJS.
Why Get the User’s IP Address?
You might need to track the IP Address for a number of reasons, logging, adjusting the pricing of a product/subscription based on the country, checking if an IP has been blocked, or adjusting the content served based on the IP Address.
How to Get The User’s IP Address
When a user requests something from your server, it’s always accompanied by their originating IP Address.
In any language, you can only get the user’s IP when you have access through the incoming request object. In NextJS, this is accessible in the middleware, getServerSideProps (SSR), or API routes.
Getting the IP inside NextJS middleware
You can use middleware to get the user’s IP in NextJS, by using the NextRequest object:
#middleware.ts
import { NextRequest, NextResponse } from "next/server";
export async function middleware(request: NextRequest) {
const res = NextResponse.next();
let ip = request.ip ?? request.headers.get('x-real-ip')
const forwardedFor = request.headers.get('x-forwarded-for')
if(!ip && forwardedFor){
ip = forwardedFor.split(',').at(0) ?? 'Unknown'
}
return res;
}
Also note that inside middleware, you won’t be able to pass the IP back to the client-side unless you write it using cookies.
//middleware.ts
...
export async function middleware(request: NextRequest, _next: NextFetchEvent) {
const res = NextResponse.next();
let ip = request.ip ?? request.headers.get('x-real-ip')
const forwardedFor = request.headers.get('x-forwarded-for')
if(!ip && forwardedFor){
ip = forwardedFor.split(',').at(0) ?? 'Unknown'
}
if(ip){
res.cookies.set("user-ip", ip, {
httpOnly: false,
});
}
return res;
}
In the front-end, we create a custom hook to access the cookies:
// uils/useUserIp.tsx
import { useEffect, useState } from "react";
import cookies from "browser-cookies";
export const useUserIp = () => {
const [ip, setUserIp] = useState<string>("");
useEffect(() => {
const userIp = cookies.get("user-ip") ?? "";
setUserIp(userIp);
}, []);
return ip;
};
And use it in a component:
// pages/index.tsx
import { NextPage } from "next";
import React from "react";
import { useUserIp } from "utils/useUserIp";
const HomePage: NextPage = () => {
const ip = useUserIp();
return (
<div className="container">
<p>Your ip: {ip}</p>
</div>
);
};
export default HomePage;
By using non-HTTP cookies, we can access get the user’s IP even if the page is statically generated.
Getting the IP inside getServerSideProps
Getting the IP Address is similar to middleware, we rely on the request and incoming headers:
// pages/ssr.tsx
import { GetServerSideProps, NextPage } from "next";
import React from "react";
type Props = {
ip: string;
};
const SSRPage: NextPage<Props> = ({ ip }) => {
return <div>IP: {ip}</div>;
};
export default SSRPage;
export const getServerSideProps: GetServerSideProps = async ({ req }) => {
let ip = req.headers["x-real-ip"];
if (!ip) {
const forwardedFor = req.headers["x-forwarded-for"];
if (Array.isArray(forwardedFor)) {
ip = forwardedFor.at(0);
} else {
ip = forwardedFor?.split(",").at(0) ?? "Unknown";
}
}
return {
props: {
ip,
},
};
};
Unlike middleware, the getServerSideProps request object doesn’t provide us with .ip property so we use the headers.
Getting the IP inside an API route
Similar to the previous two, we still rely on the incoming headers to get the IP address inside an API route.
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
ip: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
let ip = req.headers['x-real-ip'] as string;
const forwardedFor = req.headers['x-forwarded-for'] as string
if(!ip && forwardedFor){
ip = forwardedFor?.split(",").at(0) ?? "Unknown";
}
res.status(200).json({ ip: ip })
}
Code and Demo
You can access the full code in this GitHub repository You can check the demo at this link: https://next-user-ip-tutorial.vercel.app/ . The index page represents the middleware + cookies technique. You can navigate to /ssr page or /api/hello for the other two.
Conclusion
We learned how to get the user IP address in a nextJS Application.
If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on Twitter .
Resources
Credits: Image by Monica Volpin from Pixabay


