7

I'm trying to set up server push with cloudflare, but they require multiple link header fields to push multiple files. However, I can't find any documented way to include multiple header fields with the same key in node.js. I tried providing an array, but that just concatenates them together as the value for a single header field.

TimE
  • 2,800
  • 1
  • 27
  • 25

1 Answers1

10

express

You pass an array of values to res.header('HeaderName', arrayOfValues). Here's a working example and cURL output showing the duplicate response headers. This is not directly documented, but it does work (express@4.14.0).

const express = require('express')
const app = express()
app.get('/', (req, res, next) => {
  res.header('Link', ['Link1', 'Link2'])
  res.send()
})
app.listen(3000)

curl -v localhost:3000 output:

< HTTP/1.1 200 OK
< X-Powered-By: Express
< Link: Link1
< Link: Link2
< Date: Fri, 09 Sep 2016 01:44:22 GMT
< Connection: keep-alive
< Content-Length: 0

node core http

Use res.setHeader(name, arrayOfValues)

const http = require('http')

const server = http.createServer(function (req, res) {
  res.setHeader('Link', ['Link1b', 'Link2b'])
  res.end()
})
server.listen(3000)

curl output:

< HTTP/1.1 200 OK
< Link: Link1b
< Link: Link2b
< Date: Fri, 09 Sep 2016 01:52:53 GMT
< Connection: keep-alive
< Content-Length: 0
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • Thanks, I did try that, but oddly on my local machine the header came up as comma separated values such as `Link: Link1b, Link2b`, yet when I ran the same server on a heroku test server they came up as separate `Link` fields. Both servers are running node 5.2.0, so I'm not sure what's causing this odd behavior. – TimE Sep 10 '16 at 17:07
  • Most likely different node versions. I would check your environment details very carefully. – Peter Lyons Sep 10 '16 at 17:19
  • Yeah, that was my first thought too, but that wasn't it. It turned out to be my browsersync proxy was for some reason doing the combining. I'm guessing whatever proxy method it's using re-interprets the header fields. Thanks for the help! – TimE Sep 12 '16 at 17:10
  • FYI `res.header()` is an alias for [`res.set()`](https://expressjs.com/en/api.html#res.set) – galki Dec 01 '19 at 02:25