14 ms·
LiveView Is Best with Svelte
- rc_mob 2y agoI'm a noob but it looks like this overlaps with nextjs a lot?
- PKop 2y agoLiveView and Elixir/Erlang have stateful processes on the server unlike pure stateless HTTP request/response. This fundamental difference is what makes LiveView unique. Next.js isn't passing messages over a websocket nor holding stateful processes on the server.
- POiNTx 2y agoI created LiveSvelte, let me know if you have any questions :)
- wturner 2y agoIs there any reason you can think of to still use JS Hooks if using LiveSvelte?
- POiNTx 2y agoWith hooks you are able to render your html server side while still having some js functionality. Technically you can also render server side with LiveSvelte as it supports SSR out of the box, but this SSR uses Node and that introduces a slight performance decrease (around 3ms I believe). I've been looking at Bun to see if it would help but it's still unclear to me. Heex rendering is just way faster. If you don't care about SSR for certain components (for example modals, they don't need SSR generally), then I don't see a clear advantage for hooks.
- victorbjorklund 2y agoIf you just need one simple thing in your app that uses JS it might be overkill to bring in LiveSvelte only for that.
- POiNTx 2y agoThat's true. And another downside is that once you're in the Svelte environment you can't use your Phoenix components inside those Svelte components. I've thought about adding a library of default Svelte components which mirror the core components you get from Phoenix out of the box. But then again you lose forms and changesets etc, it's just annoying. Where I see LiveSvelte fit is where you really need a lot of complex client side state. Sprinkle it in, but keep using phoenix components as your default, even with hooks
- kevinak 2y agoGreat project! Superb timing here. Just released our Svelte Radio episode about this: https://www.svelteradio.com/episodes/phoenix-liveview-and-svelte-with-wout-de-puysseleir https://www.svelteradio.com/episodes/phoenix-liveview-and-sv...
- xrd 2y agoI'm so excited about this, I've never been able to rectify LiveView and Svelte. I love hearing about the philosophies of Svelte builders so this will be an extra special episode.
- bogwog 2y agoSo instead of managing state on the client, you manage state on the client and the server? That doesn't seem like an improvement, even if it saves you from having to build yet another API.
- kevinak 2y agoSome things just end up being a better experience fully client-side. Don't go all in on it - just do it when it makes sense. Another thing I like about this is the ability to be able to use Svelte as a templating language rather than Heex.
- pjmlp 2y agoIt is just a new generation rediscovering ColdFusion, Web Forms, JSF, PHP, Spring, Rails...
- dns_snek 2y agoCould you elaborate? I don't see many similarities between those and LiveView. The difference between traditional technologies that render HTML server-side and LiveView, is a persistent connection to the server which allows it to re-render templates in response to server-side events and patch client-side HTML without writing any Javascript.
- pjmlp 2y agoMostly based on WebSockets and Server Push. As one example of such approaches, .NET has SignalR since 2013. And WebForms could use designer tooling since 2001, and then there was ASP.NET AJAX Control Toolkit.
- pdimitar 2y agoBut it doesn't have the BEAM VM. The runtime matters a lot, and LiveView wouldn't work as well if it wasn't running under the BEAM.
- bcardarella 2y agoWe use Svelte along with LiveView in BeaconCMS. There are certainly good use cases for wanting something that has more granular control of the UI on the client but I would caution teams from just going all-in on Svelte + LV for all things. Even with Phoenix using LiveView isn't always the answer as sometimes dead render pages are perfectly fine. Don't all-or-nothing everything. As the article points out there are some good use cases for deviating from the 'LiveView Way'. I would argue that if you have 1,000ms round trips then there is something else to consider but geographically located servers could be unavailable to your team for a number of reasons (i.e. cost) so adding some client-side state management could be your solution.
- submain 2y agoI am not familiar with LiveView, so I'm curious. Looks like it processes UI actions server side. So, are all client interactions sent through the websocket? I remember years/decades ago we used to do that with ASP.NET, where every single component interaction was handled by the server. How is this different / better?
- bcardarella 2y agoI never used ASP.net so I cannot offer a comparison about what is "better" but your assumption is correct that diffs are through a WS and merged client-side. What this has resulted in is actual order of magnitude of implementation time reduction over the crazier SPA complexity available today. Less time to build, less cost to the company, less bugs in the long run, and a single place to manage and reason about state. It's a win.
- bornfreddy 2y agoBut isn't there a delay in UI responses because of latency then?
- cess11 2y agoSure, it's not for a smooth user experience over 2G connection, if that's your audience you'd use ordinary template rendering with Phoenix, or use it for a JSON API and build a JS client that talks to it.
- bornfreddy 2y agoI can see the next big thing coming: no latency! Render in client! :)
- cess11 2y agoSeems maybe messy to have templating in the client but I'd take a look if someone has done it.
- klabb3 2y agoGenerally speaking this is the model I’ve always been wanted to build apps in. Event oriented, bidirectional realtime updates with server, ordered events, local and remote state... I didn’t know about LiveView and never used erlang-family languages, but definitely they’re onto something. The traditional request-response model is many times causing a lot of subtle problems with consistency and staleness. A wishful (probably also controversial) thought: if the last decade was about integrating FP concepts into mainstream languages, then I hope the next decade will be oriented around integrating stateful message-oriented (reactive?) programming into the mainstream full stack.
- nmk 2y ago> I hope the next decade will be oriented around integrating stateful message-oriented (reactive?) programming into the mainstream full stack Also known as MVC before Rails decided to redefine the term.
- DonHopkins 2y agoJava redefined the term MVC a long time after Smalltalk originally defined the term in the 70's. Rails didn't redefine the term, it much later copied the (poorly) redefined term from Java and tweaked it a little. Smalltalk MVC and Java/Rails MVC are EXTREMELY different. Java and Ruby's MVC are quite similar (and loosely based on a superficial misunderstanding Smalltalk's MVC).
- klabb3 2y agoMaybe? Most good ideas have been out there for decades. Getting the execution right is what’s hard.
- andrewflnr 2y agoNo, MVC is at best orthogonal to message-passing.
- cess11 2y agoYou can use asdf to install erlang/BEAM/OTP and elixir, takes a few minutes if you have some previous experience with the tool. Either way it'll probably take about two hours to have your first rudimentary Phoenix chat application loaded in a browser if you follow some guides and tinker around a bit.
- fearthetelomere 2y agoThis looks super promising... I very much relate to the dropdown example, and I've found that complicated UX patterns can be extremely awkward to implement and maintain in LV. One example from my experience that was prickly to implement in LV was graying out a chat message you sent if it didn't get acked or persisted by the channel/server for any reason. Can't wait to try this out in my next project!
- nvegater 2y agoI honestly don’t understand how’s this different from react server components with nextjs but with less features? It seems like the same thing but with an even clearer border between server/client components and therefore missing all the optimizations (like streaming). Like islands architecture but made out of different technologies, is my understanding correct ? I would appreciate some feedback :)
- bcardarella 2y agoLiveView has streaming. I would argue that if you're stuck in the React way of thinking about application design then it's not worth trying to sell you on what LiveView is doing. But there are multiple case studies out there showing that it results in far less build times than React for no compromise on user experience.
- terandle 2y agoYeah I wish this article had covered how this solution compares to React Server Components as it kind of looks like spaghetti of different techs compared to how next.js streamlines the same problem space into one consistent mental model.
- atonse 2y agoI've wanted something like this for Vue/React too with LiveView, because then you get access to this massive ecosystem of great components to put in your phoenix apps while still utilizing LiveView. (the LiveView component ecosystem is tiny). So maybe this can be the start of a general bridge that can bridge LV with React or Vue components too? And make it easy to put these in a page and interact with LV events, etc.
- yurishimo 2y agoThere is an adapter already for Inertia.js and Phoenix. https://github.com/devato/inertia_phoenix https://github.com/devato/inertia_phoenix
- dugmartin 2y agoI created a useLiveView() hook a couple of years ago for a couple of personal side projects. It was pretty straightforward and let me have bi-directional state. The only big downside is you also need to setup server side React rendering for the initial load if you care about SEO. Maybe I should dig it up and post it in a gist somewhere (I don't want to maintain an open source library for it).
- bezieio 2y agoI've recently developed a LV/React bridge and am using it on a production app, but nothing open sourced at the moment. I'll open it up at some point soon and try and post back here!
- atonse 2y agoEven putting it in a gist would be a great start! Looking forward to it.
- baskind 2y agoNice solution! In my app, I use reusable Stimulus controllers alongside LiveView, and it works seamlessly as well. On a general note, while it's a pleasure to build with LiveView, the more I use it in real-life scenarios, the more I realize the benefits of stateless HTTP frameworks like Hotwire, which feel more performant and resilient to reconnections, and avoid the need to place more servers close to users for stability.
- MatthiasPortzel 2y agoWhen Stimulus/Turbo was first announced, I was really hoping it would help with the problems that the author describes. Unfortunately, Stimulus doesn’t actually provide an elegant way to keep state on the client. “A stimulus application’s state lives as attributes in the DOM.” This means that it’s not better than vanilla JS or jQuery. Edit: I haven’t used Stimulus for a real project; it’s possible their values and change callbacks are a better experience than I originally imagined.
- sph 2y agoYeah I use Stimulus and Live View together as well. It is the right level of complexity, while I feel Svelte deals with a lot of stuff which is not even an issue when paired with LV. All you need is vanilla JS or a thin layer on top of it, not an entire framework. You will not have to write a lot of JS after all. My production app has no more than 200 lines of JS, and I could probably get rid of a couple Stimulus controllers. Live View is that good. I also made a very hacky Stimulus-Live View hook adapter, so my Stimulus controller can send events directly to the LV process. EDIT: Live View does not require you to run geo-distributed servers at all, unless you have bought into the fly.io kool aid a little too much. And it deals with disconnections beautifully. I didn't even have to do anything to support zero-downtime updates. The client loses connection to the WebSocket and reconnects to the new version, restores the state, all that out of the box automatically. What more do you need?
- baskind 2y agoI have the same view of an app implemented with Rails+Turbo and a duplicate in Elixir+LiveView. Performance is comparable when I am close to the server (elixir is slightly faster), but when on another continent any content changes/navigation over websockets suddenly feel very laggy, while navigation over HTTP in the supposedly slower Ruby+Rails is actually consistently fast. I’ve only recently discovered this as I went travelling to another continent, so will do more perf testing. But the nature of the always-connected websockets hasn’t been a pleasurable one for me: for instance, a LiveView process crashes and you lose all the data in a big form, unless you write glue code for it to restore. And the experience of seeing the topbar getting stuck in the loading state the second your internet connection is spotty or if you are offline just gives me anxiety as a user.
- stsrki 2y agoEssentially, it works the same as Blazor Server. Or am I wrong?
- bgdkbtv 2y agoAFAIK Blazor and Livewire (Laravel) were both inspired by LiveView.
- jmull 2y agoI guess it's fun to build things, but this mashup is pretty messy. If you like Svelte (I do) you're probably going to find sveltekit to be a lot simpler and more useful.
- amsterdorn 2y ago+1, SPA should only be used as a last resort, not sure why the article compares only to it. SvelteKit is much simpler and well-documented and addresses the issues mentioned.
- peterisdirsa 2y agoIs LiveView same as Vaadin in Java world?
- cess11 2y agoNot really, Vaadin is mainly a UI component lib and some convenience annotations, while LiveView is designed to allow soft-realtime UI views over WebSocket.
- debussyman 2y agoI love LiveView + Svelte! (I gave the talk at ElixirConf 2022 on how to combine them, but the live_svelte contributors have done the work to make it a reality) IMO there is always a need for client side state, especially for apps with rich UX. I also live in NYC where network connectivity is not a given, especially in transit. One super powerful feature that the authors don't cover is being able to use Phoenix's pubsub, so that server-side state changes that occur on other servers also get pushed reactively to any client. It's pretty typical to have multiple web servers for handling mid/high levels of traffic.
- logicallee 2y agoHow usable are LiveView pages while offline? (Due to intermittent lack of network connectivity.)
- victorbjorklund 2y agoLiveview does not work at all while offline. If you just experience a short temporary drop it can reconnect you automatically.
- POiNTx 2y agoOut of the box, they don't work offline. But there's recently been a project showing it's possible to create a PWA with CRDT's and LiveSvelte: https://github.com/tonydangblog/liveview-svelte-pwa https://github.com/tonydangblog/liveview-svelte-pwa
- realusername 2y agoIt's the same as any other web page, it doesn't work when you receive or send data from the server. Liveview isn't that special, the liveview paradigm works best for what would already be online actions in a normal page.
- matlin 2y agoMobile networks in general also produce a lot of latency and often warrants a local first caching system on the client. If you want a LiveView like user experience but resilience to flaky network conditions, we just added Svelte 5 bindings to Triplit[1] which let's you write queries client-side and have them sync with a server over web-sockets. Probably not attractive to Elixir devs but if Svelte is your central focus, Triplit is a good option. [1] https://www.triplit.dev/docs/frameworks/svelte https://www.triplit.dev/docs/frameworks/svelte
- fizx 2y ago> There is a (literal) speed of light limitation with this approach: your server can only be so close to your users. The next step is to compile your server to WebAssembly and ship it to your clients. You can then use it to optimistically render responses while waiting for the real server to return. Sounds a little crazy, but we've actually pulled it off for a project, and its magic.
- CSSer 2y agoWow, that sounds cool! Can you share any more details?
- kevinak 2y agoWhy wouldn't you just use a Service Worker for this?
- AirMax98 2y agoThere's a couple different ways to skin this cat, but WebAssembly is definitely the "coolest". I'd imagine even a Service Worker is overkill compared to just inlining an optimistic response in whatever rest client you're using. Kind of similar to the content of this article, I wish people were more upfront with their reasoning. Doing something because "it's rad" is definitely fine by me!
- postalrat 2y agoIt sounds over-engineered. Lots of over-engineered stuff gets pulled off for no good reason.
- digdugdirk 2y agoFor someone not in the web dev space, this looks like an interesting way to get started. If one has Python and Rust experience, what would be a recommended "first principles" path to get started in understanding web development with LiveView and Svelte?
- kevinak 2y agoStart with Phoenix and add live_svelte when you need to. No need to juggle both at the same time when you're starting out.
- dinkleberg 2y agoI would advise against that path (unless you’re looking at a long time horizon). Phoenix is great, and it makes a lot of really hard things simple, it also introduces you to a lot of things that don’t exist anywhere else (relies heavily on OTP). But then that approach has almost nothing to do with svelte or any other SPA tool so that is something else you’d have to learn. Personally I’d start with either Phoenix and avoid any SPA tools until you get really comfortable and have hit the boundaries of what is possible with Phoenix. Or alternatively, I’d start with sveltekit and not think about Phoenix and save exploring that for another time. Phoenix is super cool, but I’d suggest starting with SvelteKit, as you can build full stack apps and the same principles apply if you want to move to react or vue or anything else.
- todotask 2y agoI wonder what happened when attempting to open this website, as it caused my Firefox browser to hang. I've never experienced such a problem before.
- enraged_camel 2y agoThe biggest benefit to this would be gaining access to all the UI component libraries in the JavaScript ecosystem. The lack of such components in LV is one of the things that slows us down the most.
- chimen 2y ago90% of those components are in/for React tho?
- furyofantares 2y agoA pattern sometimes used in multiplayer video games is there's a bunch of code that is by default run on both the client and the server. The client code runs as a prediction of the server state. When the server state is received it slams the client state. For games "prediction" is an apt description of this, because the client can make a good guess as to the result of their input, but can't know for sure since they don't know the other players' inputs. But this paradigm can also be used to simply respond immediately to client input while waiting for the official server state - say by enabling/disabling a dropdown, or showing a loading spinner. There's also plenty of client state that's not run on the server at all. Particle systems, ragdolls - stuff that doesn't need to be exactly the same on all clients and doesn't interact with other player inputs / physics. If we're gonna have a persistent server connection I don't see a reason this wouldn't work in a reactive paradigm.
- POiNTx 2y agoThat's what I did with: https://territoriez.io/ https://territoriez.io/ It's a clone of https://generals.io/ https://generals.io/ It's built with LiveSvelte. It doesn't need any predictive features as it's basically a board game and runs at 2 ticks per second. It does use optimistic updates to show game state before it actually updates on the server. The server overrides the game state if they're not in sync. All game logic is done inside Elixir. To do predictive correctly, you'd need to share logic between the server and the client. Otherwise you're writing your logic twice and that's just a recipe for disaster. One possible solution which I didn't investigate, but should work, is to write all game logic in gleam (https://gleam.run/ https://gleam.run/). Gleam is compatible with Elixir, AND it also can compile to js, so you could in theory run the same code on the server and the client. Now this is a big mess to understand, you could say "why don't write it all in js and be done with it" and you'd make a very good point and I'd probably agree. The main advantage you get is that you can use the BEAM and all it's very nice features, especially when it comes to real time distributed systems. It's perfect for multiplayer games, as long as you don't take into account the frontend :)
- djbberko42 2y agoAs someone who started using Elixir this year (for work) this is really cool. I have had some ideas for some SPAs and games just like these io ones and it'd be great to use Elixir for them. Do you think a top down fps io game would be plausible with this setup? There would need to be at least 60 ticks per second I'd think.
- jonnycat 2y agoThis is great. LiveView is truly amazing and greatly speeds up development, but as the post describes, there are a couple of rough edges. They're all solvable, but sometimes there aren't clear or well-established patterns for how, so it can feel a bit ad hoc. While I'm not currently using Svelte for this kind of thing, I'm really glad to see people formalizing some of the issues + solutions.
- atonse 2y agoMy main complaint with LiveView is communication between components in a tree (like callbacks and sending data back). It’s still janky at a core syntax level between send, send update, etc. I feel this is something only the core team can fix because it probably requires some kind of use of macros etc.
- krainboltgreene 2y agoMy own company has found significant advantage by using LiveView with Alpine, specifically in CSP mode since we can't allow `eval` to happen on the client. When I originally looked at LiveSvelte it seemed very new and untested. It also had some unsolved implications in strict CSP environments. Glad to see that it's become very useful! Our own pattern (LiveAlpine?) is as follows: Does the component need HTML? Then use an HTML Component. Does the component have server-side state? Then use a Live Component. Does the component need client-side behavior and/or state? Then also define an Alpine component. Does the component need to receive client-side events from the server or make HTTP requests? Then also define a Phoenix Hook.
- scop 2y agoThank you for providing your pattern.
- kimi 2y ago> What's most game-changing, though, is that you have a backend, stateful process that is collaborating with a frontend, stateful process. ...given that managing state is the thorniest of issues, what could go wrong with this approach?
- mattbrewsbytes 2y ago> LiveView makes a lot of things easy. But it also makes some easy things hard. Having been involved with web applications for a couple decades there were some weird things LiveView did that weren't easy for me to pick up. Maybe its changed in the last 12-18 months but initial versions were built odd for some seemingly easy types of XHR things one would want to do.
- moomoo11 2y agoAnyone else use this in production with a significant user base or business usage? How’s ur experience?
- sebastianconcpt 2y agoHave you guys considered htmx before going that way? If you can share pro/cons I'd love to hear.
- _acco 2y agoAuthor here. We did not. We briefly tried Alpine, which I think is comparable? I think Alpine is cool, but it didn't really stick with the team. I think that's because we were still writing our components in LiveView and sprinkling in Alpine. A big unlock with LiveSvelte was getting to move so much into `.svelte` files, but not converting the whole thing to a SPA. Working in a `.svelte` file gives you a lot of niceties that an Alpine-decorated LiveView component won't (prettier, intellisense, etc). This approach could totally work with other paradigms, like Alpine and HTMX. I think the key is using LiveView as a backend-for-frontend, so writing all your components in `.htmx` files or whatever.
- brushfoot 2y agoAlpine isn't really comparable to HTMX, though their names often come up together. Alpine is something like "AngularJS lite," a lightweight JavaScript framework with some similarities to the original version of Angular. HTMX is a collection of HTML attributes that simplify replacing HTML on your page with HTML partials from your server. In the article's example of interdependent dropdowns, you'd have HTMX attributes for catching the change event of the first select, specifying the server URL to fetch updated HTML from, and specifying the target to put the HTML into (the second select). Some have recommended using HTMX for less complicated client-side interactivity and adding AlpineJS to pages that need more. That said, people have built impressive apps just by leveraging HTMX.
- lacoolj 2y agoWhen I watch people using Nextjs, it makes me cringe. "This is just PHP but less clear what happens where" And yet for some reason the thought of Phoenix + LiveView + Svelte makes me want so badly to try it. Just the thought of playing with it has me giddy. This must be a mental disorder I'm experiencing. Dissociative Framework Disorder.
- inopinatus 2y ago> If a new row comes in, you just need to push it to your table, and LiveView will update the client for you. Don’t do this in line-of-business apps where those rows are interactive. The cognitive latency readily induces users into clicking the wrong thing, emailing the wrong customer, refunding the wrong transaction etc. My preferred UX instead is a sticky banner conveying “the data has changed, click here to refresh”. Or, in a pinch, ensure that new rows are rendered append-only with no change in scroll position.
- EmilStenstrom 2y agoThis CAN work, if you animate in the new lines slowly and (maybe) disable clicks while new data is coming in.
- deleted 2y ago[deleted]
- cosmojg 2y agoI definitely prefer this over click-to-refresh banners. I want to make as few decisions as possible when completing a well-defined task on a computer.
- gardenhedge 2y agoArticle misses a comparison to newer frameworks like Remix which are server side driven
- chimen 2y agoServer side, Remix does not hold a candle against Elixir.
- gardenhedge 2y agoWhy not?
- udkl 2y agoThe cleanest way to handle the backend and frontend charade I've seen until now is using https://github.com/hyperfiddle/electric https://github.com/hyperfiddle/electric which is a clojure DSL on top of react
- uxcolumbo 2y agoThis needs to be higher up ;) Also worth checking out Dustin’s talk about optimistic UIs. https://youtu.be/v-GE_P1JSOQ?si=3tZeAZqoroN1Vubp https://youtu.be/v-GE_P1JSOQ?si=3tZeAZqoroN1Vubp And quick tutorial: https://electric.hyperfiddle.net/ https://electric.hyperfiddle.net/ Have you used electric clojure?
- mrcwinn 2y agoIf you find the need to use Svelte with LiveView, I assure you, you’re doing it wrong.
- gr4vityWall 2y agoI have the impression Meteor solves this problem really well. You get optimistic UI by default without any extra work.
- aabbcc1241 2y agoYou may give ts-liveview a try. It is easy to inline client-side script and possible to share the exact function between client and server. I suppose it's also possible with remix