A simple introduction to Phoenix LiveView

by Alexandre Dedourges, DevSec

When you want to create a client application, you may need to make it "interactive". An interactive client will allow you to answer certain problems or simply to make it more attractive. Indeed, a static web page may not meet all the needs. For example, let's take an actor of the web known by all: Google. On its map service better known as Google Maps you can interact with a map, move around, click on a sign... This would not be possible on a page not using JavaScript. But then, how to make your page more alive and moving? Very often, it is JavaScript that will help you in this task. Unfortunately, not all developers have the desire to learn JavaScipt. That's why a tool has been created to help all developers who use Elixir to create their web application. This makes it a very interesting programming language for anyone who wants to create a client application. Indeed, a framework has already been designed for web developers using Elixir. This one is called Phoenix. Thanks to it, it is easy to create a web application. It is therefore quite natural that another tool has been developed to meet the needs of developers: LiveView. This one is intended for developers who want to add behaviors similar to those offered by JavaScript.

Application with JavaScript and without, what differences?

An application that does not use JavaScript will not offer as many possibilities as an application that includes it. Indeed, JS offers an interactivity that HTML or CSS does not. It is possible to perform many actions using JavaScript. For example: display elements, hide elements, change CSS properties, change HTML attributes, display warning messages, perform calculations and display them, etc.

JS therefore allows you to perform actions that will visually affect the display of the page. This means that you don't have to reload a page when you want an element to be modified when a user clicks on a button for example. Nowadays, most web pages or web applications use JavaScript to function. Indeed, JS is still a massively used language, because no alternative manages to take over it. For web pages and web applications, it remains the dominant solution. For mobile applications, we can see a significant craze for another language: React Native. In other words, JS offers many possibilities that developers will find hard to do without. However, this implies that they have to learn how to use it, and this can put off many. This is why LiveView was developed for all Elixir developers who use its web development framework: Phoenix.

Phoenix Framework for smooth and fast applications

Phoenix is a web development framework. It is written in Elixir, which is a multi-paradigm programming language (a paradigm being a way to approach computer programming). It runs on an Erlang virtual machine (BEAM) that allows applications written in Elixir to function. Its creator, José Valim, wanted to create a programming language for large-scale sites and applications. It was created to take full advantage of the multi-core processors that began to be fully democratized in the 2000s. It is particularly used to create low-latency and fault-tolerant distributed systems.

Phoenix therefore takes full advantage of Elixir's strengths, making it a powerful tool for development. This framework implements the MVC (Model View Controller) model on the server side. MVC is a software architecture pattern for graphical user interfaces that is very popular for web applications. It is composed of three types of modules with three different responsibilities: models, views and controllers.

Model View Controller (MVC)

MVC : source https://rosedienglab.defarsci.org/a-quoi-sert-une-architecture-mvc-son-fonctionnement/

This type of model allows a better distribution of tasks by separating the business logic and the display.

The strength of Phoenix is that it combines productivity and performance. Indeed, it offers a great development capacity and very high application performance. In addition, certain libraries allow it to be used to its full potential, such as LiveView.

LiveView, a major advantage for Elixir developers

LiveView is a library for Elixir and more particularly for its Phoenix framework. This one will allow more interactive pages or applications. Which will allow users to change the behavior of the page based on their actions. This one was imagined and created in 2018 by Chris McCord. He tells us more about LiveView in an article published on Dockyard

« P**hoenix LiveView is an exciting new library which enables rich, real-time user experiences with server-rendered HTML. LiveView powered applications are stateful on the server with bidirectional communication via WebSockets, offering a vastly simplified programming model compared to JavaScript alternatives. »**

So we learn here that LiveView allows real-time rendering of HTML via the server. In other words, it allows to create HTML pages on the server side and send them to the browser. This is called Server Side Rendering (SSR). We also learn that applications using LiveView are "stateful". This means that they store additional information on the server side. Here, a stateful view listens for events in a particular sequence or combination before generating a single top-level event. It is the server that will modify the view based on the events and user data. With LiveView you simply write HTML templates and a stateful process synchronizes them with the browser, updating it only when necessary. There is no JavaScript to write and developers can continue to write and test their code in the same language: Elixir.

In addition, LiveView uses WebSockets for bidirectional communication, i.e. between the client and the server. LiveViews react to client events, as well as to server-side events, and return their rendered updates to the browser.

Stateful vs. Stateless

A stateful application stores client session data. This data can be information about previous client requests, login/authentication status, etc. This data is stored on the server on which the application runs or on another server.

In contrast, a "stateless" application does not keep any data about the user session on the server from which it is running. The data can then be kept in the client's cache via cookies for example. 

Both methods are widely used and each has its advantages and disadvantages. Nevertheless, rendering pages on the server side allows to lighten the client and therefore to increase the performance on its machine. 

How LiveView works

A live view starts by rendering a so-called stateless page to the client. After an HTTP request the user will see a page displayed. This page will be a simple HTML page that can be displayed even if JavaScript is disabled in the user's browser. This is already a significant advantage. Then a communication will be established between the client and the server. One passes then on a stateful view. This view will wait for events from the client (clicking on a button, filling in a form...) or changes of state on the server side. If an event or a change occurs, the view will be rendered again. 

LiveView operation diagram

LiveView operation diagram

Source : https://elixirschool.com/images/live_view.png

How to install LiveView?

To use LiveView, you have two options  :

  • If you want to create an application from scratch. Use the following command (on Phoenix versions 1.5+) :
mix phx.new my_app --live
  • If you want to create an application from scratch. Simply use the following command (on Phoenix 1.6+ versions) :
mix phx.new my_app
  • If you want to add LiveView to your existing project, simply follow the steps in the official Elixir documentation : LiveView Installation

Taking advantage of LiveView

Once LiveView is installed, we need to learn how to use it. 

To start using LiveView, you need to understand that a LiveView is really just a module that looks like this :

code

A LiveView is composed of two functions. A "render" function which takes as parameter "socket.assigns" and a "mount" function which takes as input parameters, a session and a socket.

When our application receives an HTTP request pointing to a page using our LiveView, it will respond by displaying the static HTML page defined in our "render" function. To do this, the "mount" function will first be called. This function will assign default values to our socket which will then be used in our "render" function. These are steps 1, 2 and 3 of the diagram we saw earlier in this article :

LiveView operation diagram

Once the first 3 steps are completed, the client should normally have a static HTML page displayed. He will then send back his signed session (thanks to the signing salt defined previously in « config.exs ») to the server (step 4). The server will then open a stateful connection between itself and the client (step 5). This will have the effect of "updating" the page display each time the socket is updated. 

Now let's take a closer look at our "render" function.

code

As you can see, this one contains a "~H" sigil. This sigil is used to define an HEEx (HTML + EEx) template. This is an extension of the Elixir EEx templates, with support for HTML validation, etc.

To use your newly created LiveView, you now have two choices to use it directly from your router in this way :

code

Or use the "live_render" function in your templates. You will then just have to import in your « Phoenix.LiveView.Helpers » view, and in your template and use "liver_render" like this:

code

Now that we have the basis of our LiveView, let's see how it works when it receives an update from the socket.

Let's say you have the following render function:

code

The "phx-click" button will send the "click" event to the server when the client has clicked on the button. This event will then be managed by the server and more specifically by our LIveView. 

These events are managed by the "handle_event" function, so we can imagine a function that would look like this:

code

The "handle_event" function takes as parameters the name of the event, a value and the socket. This function will allow you to perform the action associated with the event. Here the temperature increases and the update of the text that will be displayed. Indeed, the value of the key " :status " will be updated in our socket. This will cause the part of the page that contains  **<%= @status %>** to be updated. The user will then see "Status : No event" being replaced by "Status : Temperature increased".

After clicking on the button the page display will change from :

BUTTON
Status : No event

To this:

BUTTON
Status : Increased temperature

That's it! You have just created and used your first LiveView! 

LiveView, a powerful tool

As we have seen, LiveView is a very interesting tool that comes to help developers who do not want to use JavaScript, or at least do not want to bother with the syntax of JavaScript. Thanks to LiveView, developers can concentrate and focus on a single language: Elixir. LiveView also allows you to make your pages "stateful" and to do more things on the server side. This will result in a lighter load on the client. Moreover, the reduced use, or even elimination, of JS reduces the risks associated with the disadvantages of JS (JS visible to all, incompatibility with certain browsers or browser versions, very strict syntax, etc.).

In other words, LiveView will offer better performance to the client, but also more security while removing the drawbacks of JavaScript. 

If you want to learn more, feel free to contact us, read our other articles or visit our social networks like LinkedIn, or Twitter !

Add enterprise SSO for free

Cryptr simplifies user management for your business: quick setup, guaranteed security, and multiple free features. With robust authentication and easy, fast configuration, we meet businesses' security needs hassle-free.

More articles

SAML vs SSO: Differences between SSO and SAML authentication

Uncover the key differences between SAML vs SSO in user authentication. How SAML enables SSO and their roles in enhancing identity security and login processes

Read more

A guide of Magic Link Login for Passwordless Authentication

Unlock passwordless authentication with email magic links! boost security and user experience. Discover our comprehensive guide to email magic link login

Read more