Here lies a simple(ish) pattern to build express API’s with typescript.

Why typescript for the server?

For the same reason people end up using other transpiled languages! Because I get an early warning system - for very little upfront effort. Also, it allows me use a language that reminds me of the best parts of C#, F# and javascript.

So I don’t need to write unit tests anymore?

Sorry but even though this example doesn’t come packing with tests, you should probably write tests for your production code. Not all issues are picked up by type checking.

Take a look on github

What next?

You could easily extend this example to include authentication, produce dynamic api documentation, add a database and many other types of middleware.

Break it down…


For configuring the behaviour of the typescript compiler

    "compilerOptions": {
        "sourceMap": true,
        "noEmitOnError": true
    "exclude": [

NOTE You’ll want to use typings to bring in nodejs & express definitions.


Application Class

///<reference path="./typings/main.d.ts"/>
import express = require("express");
import customerRouter = require("./routes/customerRouter");
import requestLogger = require("./middleware/requestLogger");

export class WebApi {
     * @param app - express application
     * @param port - port to listen on
    constructor(private app: express.Express, private port: number) {

     * @param app - express application
    private configureMiddleware(app: express.Express) {

    private configureRoutes(app: express.Express) {
        app.use("/customer", customerRouter );
        // mount more routers here
        // e.g. app.use("/organisation", organisationRouter);

    public run() {;  


Example express Router usage

import express = require("express");

let customerRouter = express.Router();
customerRouter.get('/', (request: express.Request, response: express.Response) => {
    let testData = {
        firstName: "The",
        lastName: "Burge"

// add more route handlers here
// e.g.'/', (req,res,next)=> {/*...*/})
export = customerRouter;


Example custom middleware implementation

import express = require("express");

let requestLogger: express.RequestHandler = (
    request: express.Request,
    response: express.Response,
    next: express.NextFunction
) => {`${(new Date()).toUTCString()}|${request.method}|${request.url}|${request.ip}`);

export = requestLogger;


Program entry point

import express = require('express');
import { WebApi } from './application';

let port = 5001; //or from a configuration file
let api = new WebApi(express(), port);;`listening on ${port}`);