Sling Academy
Home/Next.js/Next.js: How to Get User’s IP Address

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

Last updated: January 14, 2023

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.

Next Article: Next.js API Routes: How to Get Parameters & Query String

Previous Article: Route Handlers in Next.js 14: Tutorial & Examples

Series: Route Handlers and API Routes in Next.js

Next.js

Related Articles

You May Also Like

  • Solving Next.js Image Component Error with CSS Classes
  • How to Use MUI (Material UI) in Next.js 14
  • Fixing Data Update Issues in Next.js Production
  • Fixing Next.js Undefined ENV Variables in Production Build
  • Solving Next.js SyntaxError: Unexpected token ‘export’
  • Next.js Error: Found Page Without a React Component as Default Export – How to Fix
  • Fixing Next.js Error: Blank Page on Production Build
  • Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide
  • Next.js Issue: useEffect Hook Running Twice in Client
  • Fixing ‘self’ is not defined error in Next.js when importing client-side libraries
  • How to Dockerize a Next.js App for Production
  • How to set up Next.js with Docker Composer and Nginx
  • Solving Next.js CORS Issues: A Comprehensive Guide
  • Fixing Next.js Hydration Mismatch Error in Simple Ways
  • Next.js Error: Cannot use import statement outside a module
  • Next.js: How to Access Files in the Public Folder
  • Fixing Next.js Import CSS Error: A Simple Guide
  • Fixing LocalStorage Not Defined Error in Next.js
  • Fixing Next.js Error: No HTTP Methods Exported