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 };
};
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:
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.