lolo32 / fastify-sse

Provide Server-Sent Events to Fastify
20 stars 16 forks source link

Server crash when client disconnect: "Can\'t set headers after they are sent." #1

Open sylvain101010 opened 6 years ago

sylvain101010 commented 6 years ago

Hi, When a client disconnect, the server crash with the following error:

Error: Can't set headers after they are sent.

here is a stacktrace

server listening on 3000 _http_outgoing.js:504 throw new Error('Can\'t set headers after they are sent.'); ^ Error: Can't set headers after they are sent. at validateHeader (_http_outgoing.js:504:11) at ServerResponse.setHeader (_http_outgoing.js:511:3) at Immediate.wrapReplyEnd [as _onImmediate] (/Users/test/fastifyy/node_modules/fastify/lib/reply.js:145:15) at runCallback (timers.js:785:20) at tryOnImmediate (timers.js:743:5) at processImmediate [as _immediateCallback] (timers.js:714:5)

How to reproduce:

just run example.js node example.js then curl localhost:3000/sse2 And quit the running curl job Ctrl+c

YerkoPalma commented 6 years ago

I just had this very same issue. You must ensure to call reply.sse() (with no arguments) before closing your server. This works for me

fastify.addHook('onClose', (instance, done) => {
  instance._Reply.sse()
  done()
})

try adding that hook, then running your server and stop it with Ctrl + c

piranna commented 5 years ago

He is talking about when clients disconnect, that's the same problem I have, NOT when server close...