symfony / ux

Symfony UX initiative: a JavaScript ecosystem for Symfony
https://ux.symfony.com/
MIT License
843 stars 308 forks source link

[Turbo] Add `mercure()` to `turbo_stream_listen()` #1860

Open seb-jean opened 5 months ago

seb-jean commented 5 months ago

Hi,

For generate the URL of the Hub and for automatically set the cookie required to use the authorization mechanism, we need Twig helper mercure() (PR: https://github.com/symfony/mercure/pull/62)

But how to use it with turbo_stream_listen()?

Guervyl commented 5 months ago

Yes, I have the same problem. In dev mercure is working fine but in production I can't use it. I'm getting 401.

gremo commented 1 month ago

Same problem/question here.

smnandre commented 1 month ago

Could you guys set up a small reproducer app, with everything needed to test (like an example you need to work that does not today) ?

gremo commented 1 month ago

@smnandre I'll try probably tomorrow.

I'll try to explain better what I think @seb-jean is asking.

In short, mercure() helper does one important thing: it setup the cookie needed to subscribe to a topic (when authorization is needed, i.e. Mercure doesn't allow anonymous subscribers):

<script>
  const eventSource = new EventSource("{{ mercure('https://example.com/books/1', { subscribe: 'https://example.com/books/1' })|escape('js') }}", {
      withCredentials: true
  });
</script>

As you can see withCredentials is passed to the EventSource object. CORS and the cookie make the subscribe process work.

On the other hand, turbo_stream_listen does not set any cookie and does not support passing withCredentials to the Stimulus controller (let alone that the controller itself doesn't support options for the EventSource object).

So, what I think he is asking (and what I think it's needed is):

See https://github.com/symfony/ux/pull/1774

seb-jean commented 1 month ago

Yes, that's exactly it, plus the ability to subscribe to multiple topics.