0

I'm using a Fastify server to send SSE events to a React front-end. While everything worked well locally, I'm having issues once deployed behind Nginx. The front-end and the server aren't on the same domain and although I set the cors origin to be "*" on the server, and the other call resolve without issue, for the server-sent-events endpoint only I get

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/events. (Reason: CORS request did not succeed). Status code: (null).

Here's how Fastify is configured, using @fastify/cors and fastify-sse-v2

import fastifyCors from "@fastify/cors";
import FastifySSEPlugin from "fastify-sse-v2";

// ...
    await this.instance.register(FastifySSEPlugin, { logLevel: "debug" });
    await this.instance.after();
    await this.instance.register(fastifyCors, { origin: "*" });

Then sending events based on postgres pubsub with:

    await pubsub.addChannel(TxUpdateChannel);

    reply.sse(
      (async function* () {
        for await (const [event] of on(pubsub, TxUpdateChannel)) {
          yield {
            event: event.name,
            data: JSON.stringify(event.data),
          };
        }
      })()
    );

On the front-end I use eventsource so that I can add Authorization headers:

import EventSource from "eventsource";

// ...
    
    const source = new EventSource(`${SERVER_URL}/transaction/events`, {
        headers: {
            'Authorization': `Bearer ${jwt}`,
        },
    });

    source.onmessage = (event) => {
        console.log('got message', event)
        getUserData()
    }

    source.onopen = (event) => {
        console.log('---> open', event)
    }

    source.onerror = (event) => {
        console.error('Event error', event)
    }
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Tbaut
  • 306
  • 1
  • 7

1 Answers1

1

The problem was in the nginx configuration. Thanks to EventSource / Server-Sent Events through Nginx I solved it using the following placed into the location of the nginx conf :

proxy_set_header Connection '';
proxy_http_version 1.1;
chunked_transfer_encoding off;
proxy_buffering off;
proxy_cache off;
Tbaut
  • 306
  • 1
  • 7