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)
}
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 also try using page's getInitialProps.
IndexPage.getInitialProps = async ({ req }) => {
const ip = req.headers["x-real-ip"] || req.connection.remoteAddress;
return { ip };
};