light-my-request
light-my-request copied to clipboard
Multi-value request headers are serialized to comma-separated string
Prerequisites
- [X] I have written a descriptive issue title
- [X] I have searched existing issues to ensure the bug has not already been reported
Fastify version
4.23.2
Plugin version
No response
Node.js version
20.x
Operating system
macOS
Operating system version (i.e. 20.04, 11.3, 10)
13.0
Description
The .inject() method allows to inject request headers which values can be a string or an array of strings. When an array is used, it gets serialized to an comma-separated string.
Steps to Reproduce
await fastifyInstance.inject({ method: 'get', url: '/', headers: { foo: 'bar', baz: ['first', 'second'] } });
gives me the following request headers in the route handler:
{
baz: 'first,second',
foo: 'bar',
host: 'localhost:80',
'user-agent': 'lightMyRequest'
}
Expected Behavior
I would expect to get an array of strings in the route handler as well.
I would expect to get an array of strings in the route handler as well.
Fastify does nothing to the incoming headers - unless you set a json schema as validator. Headers are parsed by Node.js itself and when it gets an incoming request with multiple header's value:
curl --location --request GET 'http://127.0.0.1:8080/' \
--header 'foo: one' \
--header 'foo: two'
They are serialized into one: request.raw.headers // { foo: 'one, two' } because of the joinDuplicateHeaders set-up in Fastify: https://nodejs.org/api/http.html#httpcreateserveroptions-requestlistener
Here is further discussions:
- https://github.com/nodejs/node/issues/3591
- https://stackoverflow.com/a/36439388/3309466
You need to write an hook to run custom logic agains incoming headers.
Another solution can be to set a json schema with some plugins (not checked but I'm quite sure it exists)
BUT, I just saw this prop: request.raw.headersDistinct that works for you
https://nodejs.org/api/http.html#messageheadersdistinct
{
foo: [ 'one', 'two' ],
'user-agent': [ 'PostmanRuntime/7.29.2' ],
accept: [ '*/*' ],
'postman-token': [ 'c39ea719-7f1a-48a3-a1a5-99abdfab0f36' ],
host: [ '127.0.0.1:8080' ],
'accept-encoding': [ 'gzip, deflate, br' ],
connection: [ 'keep-alive' ]
}
But this prop is not implemented by this module and it will be undefined
So to summarize:
- the behaviour of light-my-request follows the http.IncomingMessage standard
- the
headersDistinctis a missing feature
Thanks for the explanation. I was following the type definition of RawRequest['headers'] and according to that header values could be arrays. So I’ve implement logic to handle those arrays. Now I want to write a unit test to test that logic using light-my-request. However it seems like it is not possible to create such header values. Is the type definition incorrect?