Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 499
Tithos Avatar asked Jan 31 '26 06:01

Tithos


1 Answers

Since you are using axios, you can directly pass your custom header in the header like this:

export async function getServerSideProps({ req }) {      
  const { data } = await axios(`http://ip-api.com/json/${ip}`, {
    headers: {
      'x-real-ip': **Your custom value**
    },
  });

  return {
    props: {
      location: data,
    },
  };
}
like image 187
Nihal Gupta Avatar answered Feb 01 '26 20:02

Nihal Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!