简体   繁体   中英

how to get the ip address of the client from server side in next.js app?

I want to get the user time zone and location to render a server-side page depending on the location and time zone but I can't get the user IP address from the request or get the localhost IP address (127.0.0.1). so what should I do?

You can use something like request-ip package. Then in your API route:

import requestIp from 'request-ip'

export default async function myRoute(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const detectedIp = requestIp.getClientIp(req)
}

You can also try using page's getInitialProps .

IndexPage.getInitialProps = async ({ req }) => {
  const ip = req.headers["x-real-ip"] || req.connection.remoteAddress;
  return { ip };
};

codesandbox example

Was able to detect user IP address with next.js app:

export async function getServerSideProps({ req }) {
  const forwarded = req.headers["x-forwarded-for"]
  const ip = forwarded ? forwarded.split(/, /)[0] : req.connection.remoteAddress
  return {
    props: {
      ip,
    },
  }
}

You can use the NextRequest object as a direct replacement for the native Request interface, giving you more control over how you manipulate the request. Ref: https://nextjs.org/docs/api-reference/next/server#nextrequest

NextRequest is fully typed and can be imported from next/server.

import type { NextRequest } from 'next/server'

The NextRequest object is an extension of the native Request interface, with the following added methods and properties:

  1. cookies - Has the cookies from the Request
  2. nextUrl - Includes an extended, parsed, URL object that gives you access to Next.js specific properties such as pathname, basePath, trailingSlash and i18n
  3. geo - Has the geo location from the Request
  4. geo.country - The country code
  5. geo.region - The region code
  6. geo.city - The city
  7. geo.latitude - The latitude
  8. geo.longitude - The longitude
  9. ip - Has the IP address of the Request
  10. ua - Has the user agent

Usually when the user sends a request in NextJS the request contains a socket instance that has properties, this can be the remote IP address, and remote port and other useful information.

So for anyone looking for exactly how to get this IP address of the connection remote end, you can do something like this

Login.getInitialProps = async ({ req, res }: any) => {
  const ip = req.connection.remoteAddress
  // and use some other api to get location like country from the ip address
  return { ip }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM