Svelte SSR… but it’s Java Spring Boot!

Ever since I heared the words “it’s a compiler not a runtime” I knew there had to be some implications when it comes to server side rendering, specifically in the JVM world.

Well I’m here to tell you that it is possible to render Svelte applications on a Java Spring Boot server, and I wrote a small code base that allows you to do that with a few lines of code, but there’s catch: we’ll need to setup a proper environment for it to work.

In this post I’m first going to walk through how to setup the environment and then we’re gonna write a simple SSR svelte application.

Get the template

First thing we need to clone the template that implements the code base to render Svelte.

or

now cd into your project and install the javascript dependencies

Get GraalVM

Next you need to download GraalVM.
The official website offers a community edition that is free to use and open source: https://www.graalvm.org/downloads

Target GraalVM JDK

NOTE: you could skip this step by simply setting GraalVM as your default JDK.

Throughout this guide I’m going to use NetBeans as an IDE and I’m going to make my template project target the GraalVM JDK.

This part is obviously specific to NetBeans.

  • Right click your project and open its properties
  • Check your Build → Compile configuration
  • Explore Manage Java Platforms…
  • Now Add Platform… and pick Java Standard Edition
  • And finally find your GraalVM directory and finish the configuration

Once you’re done you’ll notice that NetBeans has detected a new JDK 11 (that’s the version GraalVM offers as of this date), make sure to target that newly added Graal JDK 11 version

Install NPM dependencies

Run the following in your project root:

This will install your npm dependencies.

Now you can run your Spring Boot server using GraalVM and render svelte pages server side.

Rendering

Make a new rest controller and inject the Svelte3SSRService service, it offers a few methods you can play around with, but the main method is .page(...)

Here’s how you would use it:

You can also pass in props to your svelte page:

and in your svelte component you would export those props in order to access them, like so:

Here’s the result of this example

I hope you like it, stay safe!