1. Overview

Kotlin is a next-generation programming language developed by JetBrains. It’s gaining popularity with the Android development community as a replacement for Java.

Another exciting feature of Kotlin is the support of server- and client-side JavaScript. In this article, we’re going to discuss how to write server-side JavaScript applications using Kotlin.

Kotlin can be transpiled (source code written in one language and transformed into another language) to JavaScript. It gives users the option of targeting the JVM and JavaScript using the same language.

In the coming sections, we’re going to develop a node.js application using Kotlin.

2. node.js

Node.js is a lean, fast, cross-platform runtime environment for JavaScript. It’s useful for both server and desktop applications.

Let’s start by setting up a node.js environment and project.

2.1. Installing node.js

Node.js can be downloaded from the Node website. It comes with the npm package manager. After installing we need to set up the project.

In the empty directory, let’s run:

npm init

It will ask a few questions about package name, version description, and an entry point. Provide “kotlin-node” as name, “Kotlin Node Example”  as description and “crypto.js” as entrypoint. For the rest of the values, we’ll keep the default.

This process will generate a package.json file.

After this, we need to install a few dependency packages:

npm install
npm install kotlin --save
npm install express --save

This will install the modules required by our example application in the current project directory.

3. Creating a node.js Application Using Kotlin

In this section, we’re going to create a crypto API server using node.js in KotlinThe API will fetch some self-generated cryptocurrency rates.

3.1. Setting up the Kotlin Project

Now let’s set up the Kotlin project. We’ll be using Gradle here which is the recommended and easy to use approach. Gradle can be installed by following the instructions provided on the Gradle site.

After this, generate an initial Gradle project by using the init task. Select the “basic” type of project, Kotlin for the implementation language, Groovy as the build script DSL, then enter “kotlin-node” for the project name, and “balding” as the package name.

This will create a build.Gradle file. Replace the content of this file with:

buildscript {
    ext.kotlin_version = '1.4.10'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

group 'com.baeldung'
version '1.0-SNAPSHOT'
apply plugin: 'kotlin2js'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-test-js:$kotlin_version"
}

compileKotlin2Js.kotlinOptions {
    moduleKind = "commonjs"
    outputFile = "node/crypto.js"
}

There are two important points to highlight in the build.gradle file. First, we apply the kotlin2js plugin to do the transpilation.

Then, in KotlinOptions, we set moduleKind to “commonjs” to work with node.js. With the outputFile optionwe control where the transpiled code will be generated.

Note: Make sure that the ext.kotlin_version in the build.gradle file matches the one in the package.json file.

3.2. Creating an API

Let’s start implementing our application by creating the source folder src/main/kotlin, then the package structure com/baeldung/kotlinjs.

In this package, we create the file CryptoRate.kt.

In this file, we first need to import the require function and then create the main method:

external fun require(module: String): dynamic

fun main(args: Array<String>) {
    
}

Next, we import the required modules and create a server that listens on port 3000:

val express = require("express")

val app = express()
app.listen(3000, {
    println("Listening on port 3000")
})

Finally, we add the API endpoint “/crypto”. It will generate and return the data:

app.get("/crypto", { _, res ->
    res.send(generateCrypoRates())
})

data class CryptoCurrency(var name: String, var price: Float)

fun generateCryptoRates(): Array<CryptoCurrency> {
    return arrayOf<CryptoCurrency>(
      CryptoCurrency("Bitcoin", 90000F),
      CryptoCurrency("ETH",1000F),
      CryptoCurrency("TRX",10F)
    );
}

We’ve used the node.js express module to create the API endpoint. 

4. Run the Application

Running the application will be a two-part process. We need to transpile the Kotlin code into JavaScript before we can start our application with Node.

To create the JavaScript code, we use the Gradle build task:

./gradlew build

This will generate the source code in the node directory.

Next, we execute the generated code file crypto.js using Node.js:

node node/crypto.js

This will launch the server running at port 3000In the browser let’s access the API by invoking http://localhost:3000/crypto to get this JSON result:

[
  {
    "name": "Bitcoin",
    "price": 90000
  },
  {
    "name": "ETH",
    "price": 1000
  },
  {
    "name": "TRX",
    "price": 10
  }
]

Alternatively, we can use tools like Postman or SoapUI to consume the API.

5. Conclusion

In this article, we’ve learned how to write node.js applications using Kotlin.

We’ve built a small service in a few minutes without using any boilerplate code.

As always, the code samples can be found over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.