Next.js: How to Get User’s IP Address

Updated: January 14, 2023 By: Khue One comment

There might be cases where you want to get the IP address from where the user is viewing the current page of your Next.js app (e.g., you want to serve different content for each region or just for analytics purposes). You can do so on the server side by using the getServerSideProps() function or in API routes.

Example:

// pages/index.js
// slingacademy.com

export default function Home(props) {
  const ip = props.ip;
  return (
    <div style={{ width: '100vw', height: '100vh', padding: 30 }}>
      <h1>
        IP Address <span style={{ color: 'blue' }}>{ip}</span>
      </h1>
    </div>
  );
}

export async function getServerSideProps(context) {
  let ip;

  const { req } = context;

  if (req.headers['x-forwarded-for']) {
    ip = req.headers['x-forwarded-for'].split(',')[0];
  } else if (req.headers['x-real-ip']) {
    ip = req.connection.remoteAddress;
  } else {
    ip = req.connection.remoteAddress;
  }

  console.log(ip);
  return {
    props: {
      ip,
    },
  };
}

If you run the code above in production mode on a real server, you’ll get the real IP address. If you run it in development mode on your computer, you’ll get the result as follows:

Note: Modern computers use IPv6 by default when available. ::1 is a shortened notation of the IPv6 loopback address. The equivalent of IPv4 loopback 127.0.0.1.

Getting the client IP address in API routes is similar:

// pages/api/hello.js
export default function handler(req, res) {
  let ip;

  if (req.headers["x-forwarded-for"]) {
    ip = req.headers["x-forwarded-for"].split(',')[0]
  } else if (req.headers["x-real-ip"]) {
    ip = req.connection.remoteAddress
  } else {
    ip = req.connection.remoteAddress
  }

  console.log(ip);

  console.log(ip)
  res.status(200).json({ name: 'John Doe' })
}

Hope this helps.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments