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

Last updated on May 23, 2022 A Goodman Loading... Post a 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
// KindaCode.com

export default function Home(props) {
  const ip = props.ip;
  return <div style={{ 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 the production mode on a real server, you’ll get the real IP address. If you run it in the 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:

// KindaCode.co
// 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)
  res.status(200).json({ name: 'John Doe' })
}

Hope this helps. Further reading:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like