How would you like to use your favorite backend language to develop frontend? In this blogpost I’ll show you how to compile a small kotlin example to WebAssembly and how to run the output in your browser.

What is WebAssembly?

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable compilation target for programming languages, enabling deployment on the web for client and server applications.

Wasm is the fourth language to the browser bringing better security and performance than JavaScript. It’s an intermediate binary language supported by a growing number of languages as compilation target.

Why Kotlin?

The Kotlin native compiler uses an LLVM based backend. The same LLVM project is used for WebAssembly. It’s therefore quite easy to target wasm as a compilation target for Kotlin.

'Hello world' from kotlin in your browser console

First of all you’ll need to have the kotlinc-native compiler installed.

Let’s make a simple 'Hello World' in kotlin:

fun main() {
	println("Hello World!")

Next up, compiling: First we’ll ask kotlinc-native the possible targets

kotlinc-native -list-targets

You’ll see wasm32 in the list, this will be our target.

kotlinc-native hello.kt -target wasm32 -o hello

The output will contain a hello.wasm and a hello.wasm.js.

Let’s create an index.html

<!DOCTYPE html>
<meta charset="utf-8">
<title>WebAssembly Kotlin Demo</title>
<script wasm="hello.wasm" src="hello.wasm.js"></script>

As you can see we load both the hello.wasm.js and the hello.wasm files.

Unfortunately if you use chrome we cannot just open the html file in the browser, it’ll say: Fetch API cannot load file://temp/hello.wasm. URL scheme must be "http" or "https" for CORS request.

Use any way of serving the files to resolve this problem. For example the https rust cargo, which can be installed like this:

cargo install https

Then use http to serve . : Hosting "." on port 8000 without TLS and no authentication…​

And last but not least: open localhost:8000/index.html in your browser and check the console

Hello World!