如何在next.js应用程序中从服务器端获取客户端的IP地址?

moh*_*med 22 javascript node.js express reactjs next.js

我想获取用户时区和位置以根据位置和时区呈现服务器端页面,但我无法从请求中获取用户 IP 地址或获取本地主机 IP 地址 (127.0.0.1)。所以我该怎么做 ?

Iva*_* V. 22

您可以使用request-ip包之类的东西。然后在你的 API 路径中:

import requestIp from 'request-ip'

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


Don*_*ito 22

能够使用 next.js 应用程序检测用户 IP 地址:

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

  • 这对我有用! (2认同)
  • 这种方法可能不安全;X-Forwarded-For 可能会被欺骗,并且只有来自可信代理时才应被接受。 (2认同)

小智 6

您可以使用 NextRequest 对象作为本机 Request 接口的直接替代品,从而使您能够更好地控制请求的操作方式。参考: https: //nextjs.org/docs/app/api-reference/functions/next-request

NextRequest 是完全类型化的,可以从 next/server 导入。

import type { NextRequest } from 'next/server'
Run Code Online (Sandbox Code Playgroud)

NextRequest 对象是本机 Request 接口的扩展,添加了以下方法和属性:

  1. cookies - 拥有来自请求的 cookies
  2. nextUrl - 包括扩展的、已解析的 URL 对象,使您可以访问 Next.js 特定属性,例如路径名、basePath、trailingSlash 和 i18n
  3. geo - 具有请求中的地理位置
  4. geo.country - 国家/地区代码
  5. geo.region - 区域代码
  6. geo.city - 城市
  7. geo.latitude - 纬度
  8. geo.longitude - 经度
  9. ip - 具有请求的 IP 地址
  10. ua - 有用户代理

  • @MatheusRibeiro 另请注意,`NextRequest` 仅在 [`Edge Runtime`](https://nextjs.org/docs/api-reference/edge-runtime) 上可用。它不适用于常规 API 路由或 Node.js 服务器端代码。 (4认同)

ant*_*lis 5

您还可以尝试使用页面的getInitialProps.

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

代码沙盒示例