Getting started with serverless (offline) with express-API

Table of Content

In this tutorial I will explain step-by-step how to get started with your first serverless project using TypeScript and an express API in a local(offline) development environment by using the serverless offline-plugin.

What you need:

  • node.js (version 13)
  • a Text-Editor or a source-code-editor like Visual Studio Code
  • serverless installed
  • a terminal in which you can enter your commands (Visual Studio Code already ships with a terminal)
  • A running version of this tutorial

Step 1: Installing express and serverless-http

To use express as an REST-API-provider, we first need to install the packages we need.
Open the project-root in terminal.

$ npm i --save express serverless-http

And the type-declarations for TypeScript.

$ npm i --save-dev @types/express

Step 2: Creating the express-handler

Create a file called index.ts in your src-folder and remove handler.ts.

Add this content to your index.ts:

import serverless from 'serverless-http';
import express from 'express';
import {Request, Response} from 'express';

const app:express.Application = express();
const router:express.Router = express.Router();

router.get('/hello', (_req:Request, res:Response) => {
    res.json({ message: 'Hello World!' });

app.use('/api', router);

module.exports.api = serverless(app);

Step 3: Change bridge.js

The bridge.js also has to be changed, so that our TypeScript index.ts gets loaded.
For this just replace the String handler.ts with index.ts. You finally end up with this content.

'use strict';

module.exports = require('./index.ts');

Step 4: Change serverless.yml and run the example

In your serverless.yml change the functions-section to this.

      - http: 'ANY /api/{proxy+}'
    handler: src/bridge.api

As you can see, our new configuration is different than the one from the last example.

  • http-entry
    Here we have one entry, which routes all method-types to /api/{proxy+}.
    The proxy is letting serverless know, that all sub-routes e.g. /api/hello have to be routed to our API-handler.
  • handler-entry
    Because our index.ts exports an api-variable, we need to adjust it to bridge.api.

Run the example by executing

$ npm start

and open this URL in your browser: http://localhost:3000/api/hello.

You should see a JSON-Response with a Hello World!-message.

That’s it!

Best Page Builder Plugin
Best Digital Asset Library
Find amazing stock images
Feel free to leave a comment
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x