A guide to building a serverless microservice starter for TypeScript, Express projects with MongoDB

Danielle Klaasen
7 min readFeb 18, 2021
Unrealistic photo of clean desk, expensive sunglasses and NO coffee

Serverless is cool, microservices are awesome and combining this is just a perfect combination.

During my internship I worked for a rapidly expanding, Service-Oriented web application. The quick growth made scalability and maintenance a rising concern. At the coffee machine the lead Back End Developer introduced me to the concept of microservices, and so the story begins.

In this post I will share some of the theory I’ve learned during my research and give you a tutorial on how to build your own microservice. Basically it will be a versatile starter kit ready for any project.

Specifically the tutorial will include these topics:

  • Serverless AWS Lambda implementation
  • MongoDB connection and basic CRUD system
  • All this with Express & TypeScript integrated in your project

Get yourself some fuel and let‘s get started!

Ain’t nobody got time for manually grinding their coffee

In case you get stuck, check my git repository for the full code: https://github.com/danielleklaasen/microservice-starter

Serverless

Set up AWS Lambda cloud service

Why Amazon Web Services? Simply because it’s the most advanced one regarding serverless development at the moment. My choice was based on this article among others, read it if you’re interested in a comparison between AWS and Google Cloud Functions.

1. Create a free account here.

You will have to provide creditcard details for identification. Alternatives without creditcard are Fn, Kubeless, IBM OpenWhisk, but they don’t provide any hosting. You can use them if you prefer, but in this tutorial I will continue with an AWS account.

Create your AWS free tier account

Follow the instructions on the website and provide your details.

2. Create a user.

Search for IAM

After going to IAM, go to users in the left sidebar. Then click the button ‘add user’ and pick a user name.

Give the user programmatic access

Set permissions: attach existing policies directly and tick the checkbox for AdministratorAccess.

3. Save the Access Key ID and Secret Access Key.

Very important! You will not gain access to them after this step anymore.

Formalities are (kinda) done, yay! Let’s get coding.

Serverless framework setup

We will work with a great package called Serverless:

1. Let’s install the package.

$ npm i -g serverless

2. Set up a project from their template

We will create a project from their aws-nodejs-typescript template.

$ sls create --template aws-nodejs-typescript

3. Update the ‘service’ property in serverless.yml

# serverless.ymlservice:
name: <
ENTER-YOUR-SERVICE-NAME>

4. Install node dependencies

$ npm i

5. Connect your newly created AWS account to serverless.

$ sls config credentials --provider aws --key ACCESS-KEY-ID 
--secret SECRET-ACCESS-KEY

So far, so good. What happens if we deploy this basic setup now?

$ sls deploy
Terminal output

You can see we have 1 function available and 1 GET endpoint.

Let’s open the project in a code editor and see where they come from.

All the configurations for your service are placed in serverless.yml, on line 12 you find the available function you saw in the terminal. The endpoint follows right below. We don’t need to pay much attention to this, since we will integrate Express in a second, which will handle the endpoints for us.

# serverless.yml...
functions:
hello:
# Function name
handler:
handler.hello # Ref to exported func in handler.ts
events: # All events associated with this function
- http:
method:
get
path: hello

If you want to see what this function contains, go to handler.ts and you will see a basic hello world there.

Don’t want to deploy every time to test your code?

Serverless-offline is the solution!

$ npm i -D serverless-offline

Add this line in serverless.yml:

# serverless.ymlplugin:
...
serverless-offline

Now every time you run $ sls offline start, you can test the application on your localhost!

See full CLI reference here: https://serverless.com/framework/docs/providers/aws/cli-reference/

Typescript configuration

We are just going to set up some basics and clean up our project.

1. Go ahead and create a source directory

Let’s call it src . And also move our handler.ts in there.

2. Update serverless.yml since our handler just changed directory

# serverless.yml...
functions:
hello:
handler:
dist/handler.hello

2. Configure our typescript compiler

We expand a little on the default configuration from the template.

When you run tsc to compile, it will create a dist folder for you with the output.

Express integration

1. Install aws-serverless-express and express.

$ npm i --save serverless-http express

2. Create a new file:src/app.ts

We are going to discard handler.ts and create a new file called app.ts in our src directory. If you worked with Express before this basic setup is going to look very familiar.

The only different here is that we import from the serverless-http package. In our export function we cast our express app to serverless. They handle it from there, easy-peasy!

This file will now be our main entry for the app. You can fill that out in thepackage.json file.

{
...
"main": "dist/app.js",
...
}

4. Add our function toserverless.yml

You can remove the reference to our old handler function from the file. All of the HTTP routing logic will be done inside the Express application. Therefore we can listen very broadly to ANY/ and 'ANY {proxy+}' .

# serverless.ymlfunctions:

init:
handler:
src/lambda.init
events:
- http: ANY /
- http: 'ANY {proxy+}'

Last step in the process: MongoDB

Create a cluster

Set up a connection to your cluster

1. Install mongoose and bluebird

We will use Mongoose as a MongoDB object modelling tool and bluebird as our promise library.

$ npm i --save mongoose bluebird

Import them in app.ts

import * as mongoose from 'mongoose';
import * as bluebird from 'bluebird';

2. Connect to database

Now is the time to copy paste your MongoDB connection URL into the code.

The connection to your MongoDB will look like this:

Basic CRUD methods setup

1. Make sure we can accept JSON

For our CRUD system we will read JSON out of the request. First, we need to make sure we are able to do this, by adding body-parser.

$ npm i --save body-parser

Then, import and use it.

import * as bodyParser from 'body-parser';app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

2. Create our model

Let’s make a new directory for our model called models (surprise!). Our demo model will be a kitten in Kitten.ts. The kitten object is kept simple and only contains a name.

3. Crud methods in app.ts

Since this tutorial is already covers various topics, I will be short on this one. For in dept information about Mongoose, you can take a look at the documentation.

Below you see a basic CRUD implementation (with promises to please your inner perfectionist).

Remember to import the Kitten model.

4. Test it

Let’s start our application locally.

$ sls offline start

You can do the testing in any API development environment of your choice, I like to use good old Postman.

Create

Now, let’s try to create a Kitten. Send a POST request to http://localhost:3000/kitten with this JSON:

{"name": "Jennifurr"}

If you get the object back like this:

{
"_id": "5b0ea03ff87782579753b053",
"name": "jennifurr",
"createdAt": "2018-05-30T12:59:43.888Z",
"updatedAt": "2018-05-30T12:59:43.888Z",
"__v": 0
}

then everything works! Yay!

Read

Try to GET http://localhost:3000/kittens , you should now see your newly created Jennifurr. Copy the _id value, you will need it for the next two requests.

Update

To update you can send a POST request with a new name to http://localhost:3000/kitten/InsertIdHere. For example:

{"name": "Clawdia"}

The old object will be returned, so don’t get confused :)

Delete

Delete a kitten by sending a DELETE request to http://localhost:3000/kitten/InsertIdHere.

Photo from: http://refugeeks.com/defining-http-status-codes-list-http-status-codes/

That’s it, your microservice starter is ready!

Check the repository on my GitHub account for the full tutorial code in the tutorial branch.

Or check out the master branche for a deluxe version, which includes TS lint, unit tests, docker, health check and has a development and production environment setup. All ready to go for your next project! :)

Let me know if you have any questions or comments.

Sources

For structuring the project: https://github.com/Microsoft/TypeScript-Node-Starter#typescript-node-starter

Posts from Adnan Rahic on Serverless: https://hackernoon.com/@adnanrahic

--

--