mjl blog
March 24th 2020

Server-sent events (SSE) disconnects when clicking download link

I’m a fan of server-sent events, or SSE. They are a very lightweight option to send streaming updates from a webserver to a client. I’m using it in ding, a modest build server for small teams. Ding sends updates about a build (e.g. the build output log, build failure/success) to the browser using server-sent events. The web app uses a single SSE connection during the lifetime of the app, no matter which page (which repository, build) you’ve got open. It’s simple, and it works.

Problem

I had one problem though: When downloading a result of a build, the SSE connection would be disconnected by the browser. Firefox in my case, haven’t tried other browsers. Why does that happen? A quick internet search didn’t reveal other people, which is suspect, but also why I wrote this post.

I suspect clicking the link to download the build result triggers a “navigate away from page” event in the browser, which helpfully closes connections that aren’t needed anymore. That’s a bummer, because we aren’t really navigating away. Just downloading a file. The page remains visible. But now shows an error message about the SSE disconnection.

Solution

What is the solution? Adding a target=”_blank” to the link. Unfortunately, that causes Firefox to briefly flash a tab. It opens a new tab, immediately learns we’re just downloading, and closes the tab again. Luckily, this is easily solved by adding a “download” attribute to the link. I suspect just the download attribute is enough. But it feels young, perhaps older browsers don’t support it.

NOTE: If you are linking to an external domain, be sure to also add the rel=“noreferrer noopener” attribute along with target=”_blank”.

Summary

Use a link that looks like this:

<a href="..." download target="_blank" rel="noreferrer noopener">...</a>

Comments