Thinking about writing a custom adapter for Svelte serverside rendering (SSR) via Phoenix HTML Views

,

So I’ve been digging into svelte the last few days and I have to say I’m really hooked.

I’m not going to spend this time telling you why you should given it an honest try.

That said its still lacking something that I feel will just put it over the top as being my favorite stack.

I’m envisioning what a custom Svelte adapter would look like for doing SSR with svelte but via Phoenix Heex. I know there is already GitHub - woutdp/live_svelte: Svelte inside Phoenix LiveView with seamless end-to-end reactivity

But I want to go more abstract than that and not use really any fronted on Phoenix (ie no liveview) and just use Phoenix as a way to possible aid in doing SSR for svenlte like looking up records as a part of the initial request and inital html payload.

At the moment this is just a nebulas idea and I am looking for any input.
Thoughts? Considerations?

FYI: I’m starting with this as my first steps. Writing adapters • Docs • SvelteKit

Some initial thoughts:

  1. Request Handling: A web request is received by the Phoenix server. Phoenix’s routing determines the correct controller and action to handle the request.

  2. Invoking JavaScript Runtime: Within the controller action, the Phoenix server needs to interact with a JavaScript runtime to render the Svelte components. This can be achieved through:

    • External Node.js process: Phoenix can make a call to a Node.js process that handles the rendering of Svelte components.
    • Embedded JavaScript interpreter: Using tools like ExecJS in Ruby, though an Elixir equivalent would be needed.
  3. Rendering Svelte Components: The JavaScript runtime receives the data and renders the Svelte components server-side. This step involves:

    • Converting Elixir data structures to a format understandable by JavaScript.
    • Running the Svelte compiler to generate HTML and CSS.
  4. Returning Rendered Content: The rendered HTML and CSS from Svelte are returned to the Phoenix server.

  5. Phoenix View Integration:

    • The returned HTML can be integrated into Phoenix templates (eex or leex). Phoenix Views can then be used to inject this HTML into the overall page template.
    • Alternatively, the Phoenix response can be constructed to directly send back the rendered HTML and CSS, bypassing traditional templates.
  6. Sending Response to Client: Finally, the Phoenix server sends the response back to the client, which includes the server-rendered HTML of the Svelte components.

3 Likes