0

I am trying to retrieve a particular request header from an apolloserver request (i.e. the request object from a GraphQLRequestContext), inside a a plugin.

logging the headers object logs out as:

Headers {
  [Symbol(map)]: [Object: null prototype] {
    'content-type': [ 'application/json' ],
    user: [
      '{...(redacted)...}'
    ],
    'x-header-foo': [ '234' ],
    accept: [ '*/*' ],
    'content-length': [ '256' ],
    'user-agent': [ 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)' ],
    'accept-encoding': [ 'gzip,deflate' ],
    connection: [ 'close' ],
    host: [ 'localhost:3000' ]
  }
}

but headers['x-header-foo'] yields undefined. How do I get the header value? I have not used symbols much so far.

yen
  • 1,769
  • 2
  • 15
  • 43
  • Which middleware are you using? "*the `request` object from a `GraphQLRequestContext`*" can be [multiple things](https://www.apollographql.com/docs/apollo-server/api/apollo-server/#middleware-specific-context-fields). – Bergi Nov 10 '21 at 19:53
  • Try logging `Object.getPrototoypeOf(request.headers)`. Probably the object you've logged has methods like `.get()`. – Bergi Nov 10 '21 at 19:54
  • omg... i didn't see get() listed - but .get('x-header-foo') worked! Thx!!! – yen Nov 10 '21 at 21:02

1 Answers1

0

As you said rightly, Headers are Symbols and not Objects, so to get value, you use the get method

Read more about Symbols here Symbol is a built-in object whose constructor returns a symbol primitive — also called a Symbol value or just a Symbol — that's guaranteed to be unique.

Headers are Symbols and not Objects, so to get value, you use the get method

const host = req.headers.get("host"); // stackoverflow.com

If you wish to destructure using Symbols:

let symbol = Symbol()
let obj = { [symbol] : 'value'}
let { [symbol]: alias } = obj

console.log(alias)
Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67