How to Get User's IP Address in NextJS

Jasser Mark Arioste

Jasser Mark Arioste

How to Get User's IP Address in NextJS

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:


import { NextRequest, NextResponse } from "next/server";

export async function middleware(request: NextRequest) {
  const res =;
  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.

export async function middleware(request: NextRequest, _next: NextFetchEvent) {
  const res =;
  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'
    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") ?? "";
  }, []);

  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>
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 =;
    } else {
      ip = forwardedFor?.split(",").at(0) ?? "Unknown";
  return {
    props: {

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: 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

Share this post!

Related Posts


This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle