'How do you get "x-" headers in Next.js

I am following an example from Sara Vieira's Opinionated Guide to React. In the example, she is doing something like this:

export async function getServerSideProps({ req }) {
  const ip = req.headers['x-real-ip']
  console.log(req.headers)
  const { data } = await axios(`http://ip-api.com/json/${ip}`)

  return {
    props: {
      location: data,
    },
  }
}

My console log of the headers is:

{
  host: 'localhost:3000',
  connection: 'keep-alive',
  'cache-control': 'max-age=0',
  'upgrade-insecure-requests': '1',
  'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) 
  Chrome/86.0.4240.111 Safari/537.36',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  'sec-fetch-site': 'same-origin',
  'sec-fetch-mode': 'navigate',
  'sec-fetch-dest': 'document',
  referer: 'http://localhost:3000/',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'en-US,en;q=0.9,fr;q=0.8,ru;q=0.7,it;q=0.6'

}

None of the x- headers are coming through. I am thinking it is because I am running dev

According to https://github.com/vercel/next.js/issues/7377 the x- headers can only be accessed in _app.js or _document.js due to SSR.

Can you help!



Solution 1:[1]

NextJS built in middleware API routes does not provide req.headers. Instead you need to pass cookies on your request.

const { ip } = req.cookies

Provided you have ip name cookie with values you can destructure it on req.cookies

Here is the documentation https://nextjs.org/docs/api-routes/api-middlewares

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank Mendez