7

When I create a new EventSource in JavaScript to listen for server-sent events, like this:

var source = new EventSource("data/pushed");

Is there any way for me to specify additional headers (like some authentication token) in the outgoing HTTP request?

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234

2 Answers2

7

No, the EventSource standard does not include setRequestHeader the way XMLHttpRequest does.

It also does not support POST. But you do have cookies. So, my preferred approach for authentication tokens, where practical, is to have the user first login and create a session, and then that session cookie will be passed along with your SSE requests. (Aside: if using PHP, and using sessions with SSE, remember they are locked, so your SSE process should call session_write_close() as soon as it has validated the user. Sessions in other languages might have a similar issue.)

The only other alternative I can suggest is to use XMLHttpRequest (i.e. the Comet approach).

Darren Cook
  • 27,837
  • 13
  • 117
  • 217
2

We had similar issue, and we decided in the end to send our authorization token through URL and not to worry about security since it will be protected by SSL (in production, of course, we use HTTPS protocol).

crollywood
  • 523
  • 1
  • 6
  • 17