Home | Hello world | Component | Pursx 1 | Events 1 | Effects | Pursx 2 | Events 2 | Portals | SSR |

Server-side rendering

When performance matters!

In web development, it's good practice to send a plain-HTML version of your site over the wire before any JavaScript starts executing. This is called server-side rendering, or SSR, where the server renders HTML in an initial pass before rendering any JavaScript.

The most performant form of SSR is pre-rendering HTML and serving them from memory or from a file system. This is Deku's strategy via the following two functions:

  • runSSR generates HTML; and
  • hydrate generates JavaScript that will hydrate your HTML with anything that's dynamic. Note that this is partial hydration, meaning it will only hydrate the bits that need hydrating. This means that, for example, you can do CSS animations on load without fear of jank when the JavaScript kicks in.

This documentation is generated using SSR, and if you add view-source: before the URL, you'll see the intro page rendered as HTML. If you're reading this documentation on a computer screen, you won't see much of a difference, but if you're reading it on a 3G mobile network, you'll spot the difference immedaitely.

A motivating example

Here is a small application using SSR. We'll split it up into three files:

  • App.purs has our application logic.
  • Build.purs creates a .js file, for example make.js, that will render our HTML.
  • Live.purs uses hydration to add dynamic logic to the website.

App

Unlike the previous examples that used runInBody, our application code here has an explicit type annotation Nut. The definition of Nut is type Nut = forall s m lock payload. Korok s m => Domable m lock payload, and in larger projects, you may need to write this type out explicitly, for example if you are working with an Array of Domable and need m to be consistant over the Array.

Build

This is the code we use to generate our HTML site. The example below creates a small script that logs our HTML to the command line,but we can also call runSSR from a NodeJS server, in which case we wouldn't log the HTML string but rather we would instead send it over the wire as the response to a request.

Live

Live.purs can be bundled to generate our dynamic JS. The JS will hydrate our elements instead of replacing them, and will only hydrate elements that potentially will interactive content.

Result

Here is the resulting code from our static-site generation. It is rendered dynamically in your browser, but in production settings, we'd use NodeJS to render or pre-render this HTML.

And here is what the result looks like after hydration.

Parting shot

Thanks for checking out Deku! I had a blast writing it, and I hope you enjoy using it for your projects!