Skip to content

Writing a Backend Service in TypeScript

TypeScript is the recommended language for writing backend services. It is a superset of JavaScript that adds static typing and other features that make it easier to write and maintain code.

Prerequisites

To write a backend service in TypeScript, you should be familiar with JavaScript and (ideally) TypeScript. Overall, basic JavaScript knowledge will be sufficient to get started, but async/await and Promises are used extensively for services, so you should be familiar with these topics.

Deno

Deno is a JavaScript/TypeScript runtime that is built on top of V8, Rust, and Tokio. It is a secure runtime for JavaScript and TypeScript.

Compared to Node.js, Deno has the following advantages:

  • It has built-in TypeScript support
  • It has built-in security features
  • It’s easier to deploy

Installing Deno

To install Deno, please follow the instructions on the Deno website .

Writing a basic Service

Creating a new Service

Create a new directory for your service:

mkdir my-service
cd my-service

Create a new file called service.ts:

touch service.ts

Writing the Service

Library functions

The library for building TypeScript services is currently not hosted on a public registry. While this will change in the future, for now, simply place the lib.ts file in the same directory as your service.ts file.

Download library file

Open service.ts in your favorite editor and add the following code:

service.ts
import { startService } from './lib.ts';// (1)!

await startService/*(2)!*/({
    nats: false,// (3)!
});

console.log('Hello World!');// (4)!
  1. Import the startService function from the library. Note that the library is in the same directory as the service.ts file, so we can use a relative path.

    Later, when we publish the library to a registry, we will be able to use a URL instead.

  2. Start the service. This automatically connects to NATS and does some other setup.
  3. Disable NATS. We don’t need it for this example and it would otherwise throw an error because we haven’t configured it yet.
  4. Log a message to the console when the service starts.

Running the Service

To run the service, run the following command:

deno run --allow-all service.ts --dev

Success

You should see the following output:

Running in development mode. Using default values for missing environment variables.
Hello World!

Running in development mode

When you run the service with the --dev flag, the service will use default values for missing environment variables. You’ll learn more about this in the configuration section.

Next Steps

Now that you have a basic service running, you should have a look at how to make your service configurable.

Read more about configuration