Thanks! We'll be in touch in the next 12 hours
Oops! Something went wrong while submitting the form.

Set Up A Production-ready REST API Server Using TypeScript, Express And PostgreSQL

Birendra Bikram Singh

Full-stack Development

Introduction

So, you have a brilliant idea for a web application. It’s going to be the next big thing, and you are super-excited about it. Maybe you have already started building the perfect React/Angular UI for your app.

Eventually, you realize that, like most web apps, your app is going to be data-intensive and will need a lightning-fast web server. You know that Node.js is the de facto standard for web servers for how well it unifies front-end and back-end web development with JavaScript, so you go for it.

But you want your server to be robust and reliable too. A colleague introduces you to TypeScript, the superset of JavaScript developed by Microsoft, and recommends it for its strict static typing and compilation.

Now comes storing the data. Naturally, you select PostgreSQL. After all, it is the most advanced Relational Database Management System (RDBMS) in the world, with its object-oriented features and extensibility. But RDBMSs can be slow for frequently used data and caching, so you decide to add Redis, the in-memory cache, to decrease data access latency and ease the load off your relational data store.

That’s it. You have a perfect server waiting to be built. And while the initial process of getting it up and running can get arduous, you have come to the right place. This blog is going to guide you through the initial setup process.

Prerequisites

I am assuming you have a non-root user with sudo privileges running on Ubuntu 16.04. Before we start, please make sure you have the following: 

  1. NPM (~v6.9.0) and Node.js (~v10.16.0) – You can use this How to Install Node.js on Ubuntu 16.04
  2. Redis – How to install Redis on Ubuntu 16.04
  3. PostgreSQL – How to install PostgreSQL on Ubuntu 16.04

Of course, MacOS or Windows would do fine too for this tutorial, but to use them, please find appropriate installation guides on the Internet before moving forward. 

If you don’t want to go through the steps below, you can check out my GitHub Repo typescript-express-server and use it as your application skeleton. It has been set up with default configurations, which you can change later. Nevertheless, I strongly recommend going through this guide to further your understanding of the project files and configuration nuances.

Initializing Server (Express with TypeScript)

Setting up an Express Application with TypeScript can be done in three steps: 

Initialize project using NPM

Create a folder and run:

CODE: https://gist.github.com/velotiotech/369a5af8ce82844f64720375849c8c62.js

This will ask you a couple of project-specific questions, like name and version, and will create a package.json file, which may look like this:

CODE: https://gist.github.com/velotiotech/064b8e3cd35c2102c6e1f8efb0e7ea55.js

This manifest file will contain all the metadata of your project, like module dependencies, configs, and scripts. For more information, check out this very good read about the basics of package.json

Setting up TypeScript Configuration (tsconfig.json)

This file needs to be created in the root of a TypeScript project. During development, TypeScript provides us with the convenience of running the code directly from the .ts extension files. But during production, since Node.js only understands JS, the entire TS files need to be transpiled to JS. Some of the options are: include - specifies the files to be included, exclude -  the files to exclude, and the compiler options: outFIle and moduleResolution.

First, we need to install some TypeScript specific modules: 

CODE: https://gist.github.com/velotiotech/95b021f1728a9b8a61d9fca89b0b9e59.js

This is the tsconfig.json file with some default configurations:

CODE: https://gist.github.com/velotiotech/2cd42f3db972ebcf47d1819a80870826.j

For a detailed reference, checkout tsconfig.json.

Setting up ESLint

It is not mandatory to use this JavaScript linter, but it’s highly recommended for enforcing code standards and keeping code clean. TypeScript projects once used TSLint, but it has been deprecated in favor of ESLint.

Run this command:

CODE: https://gist.github.com/velotiotech/6b28a79d034c285a74e445e10e758649.js

Create a .eslintrc file in the project root and use the following starter configuration:

CODE: https://gist.github.com/velotiotech/9f2c1079a009c1453f9a8960317cbcea.js

Lastly, add a lint script to package.json:

CODE: https://gist.github.com/velotiotech/5a4418e83d308ea014c7e2a309cae988.js

Now, you can run the command below to lint your codebase for lint errors:

CODE: https://gist.github.com/velotiotech/b53b6acd21f1279c1711b9e6cfa38886.js

ESLint has ample rules to enforce standards in your code. Please look them up at Eslint with TypeScript.

Express App

Finally, we need to install Express, which is as simple as running this command:

CODE: https://gist.github.com/velotiotech/3935d682c9df4c5c2ae4d31846fec77c.js

You need a server file (src/Server.ts), which you can create like this:

CODE: https://gist.github.com/velotiotech/c449d81e54b81df7136b3076698efaa5.js

You will also need src/index.ts that will be the entry point for your application:

CODE: https://gist.github.com/velotiotech/4f1412ba1d345b90e6b7b95bf255ae6d.js

Error Handling

Many Express servers are configured to swallow all errors by configuring an Uncaught Exception handler, which in my opinion, is bad news. The best thing to do is to allow the application to crash and restart. Uncaught Exceptions in Node.js is a good read regarding this.

Nonetheless, we are going to configure an error handler that will print errors and send a BadRequest response when an invalid HTTP request comes your API’s way.

In the src/Server.ts, add this:

CODE: https://gist.github.com/velotiotech/bd1fbae64c7afc03ba3bebe8cf9a5f80.js

Kudos! You have a basic Express server set up. Fire it up by running:

CODE: https://gist.github.com/velotiotech/a60fb319af122a67ddaf0e5f56af5d80.js

Connecting with the Database Store using TypeORM

We have a basic server ready to go, but we need to connect it to our Postgres database using an ORM. TypeORM is a versatile ORM that supports both Active Record and Data Mapper patterns, unlike all other JavaScript ORMs. It can be installed on our server with the following steps:

CODE: https://gist.github.com/velotiotech/5d84d636b9d05c7a228a27d7e7434007.js

Create an ormconfig.json file in your project root with the following configuration:

CODE: https://gist.github.com/velotiotech/e6be0ec23cd6f81c8e5aed073a28ef2d.js

Create a src/db.ts file that will initialize the database connection:

CODE: https://gist.github.com/velotiotech/3d03479ced145cf8564f05026b9765b7.js

TypeORM Entities are classes that represent the data models in our application. We are going to build a User Entity (which application doesn’t have a user, duh!) like this in src/entities/User.ts:

CODE: https://gist.github.com/velotiotech/8589621bfc50305384a8cebbc2b3cbf5.js

Then, add these lines to src/index.ts:

CODE: https://gist.github.com/velotiotech/64af3251f7be465e2c4191c04a0ea6bd.js

You will need the env variables, like TYPEORM_CONNECTION, TYPEORM_HOST, and TYPEORM_USERNAME, with your postgres db’s connection params. Please check TypeORMs documentation for more details. 

Connecting Redis

We will use Tedis, the TypeScript wrapper for Redis in our server:

CODE: https://gist.github.com/velotiotech/ffe2783746d10c08ad19ed0796aa36a3.js

Add these lines to src/db.ts:

CODE: https://gist.github.com/velotiotech/2fb96749e512dcb9bd0b4aec2d906123.js

And these lines to src/index.ts:

CODE: https://gist.github.com/velotiotech/3ef02579bcd706e77ea63273c8f1aa99.js

Now, your application code can use the Redis cache using the client created above.

Configuring Logging

Logging is pivotal to an application because it gives us a real-time view of the state of our application. For development, we are going to install the Morgan Request Logger, a library that logs HTTP requests params. It comes really handy for debugging. 

CODE: https://gist.github.com/velotiotech/fbdfd5ccbfb758e4beaed76bf1e66087.js

And include this in src/Server.ts:

CODE: https://gist.github.com/velotiotech/9c9bbe24abf1577e44e6bd20037964ce.js

Winston can be used as the system-wide universal logger. Install it like this:

CODE: https://gist.github.com/velotiotech/abcf76b716f808efe27c421656353bf1.js

Then, add a src/shared/Logger.js file:

CODE: https://gist.github.com/velotiotech/14686ff164b30c5f92fe52fdca5346eb.js

Now, you can use this logger from anywhere in the code, be it for error logging in your API methods or for debugging purposes:

CODE: https://gist.github.com/velotiotech/87eaa841ccb46c05e597172399578ad3.js

Creating your First API Service

This is the moment you have been waiting for: creating your first API service for your application, the crux of the functionality that will define your web application.

This API service is a simple GET request handler, which returns all the users in your database. You should have src/Users.ts, which can look like:

CODE: https://gist.github.com/velotiotech/70145d85814521f2343af6b59db45634.js

Add src/routes/index.ts

CODE: https://gist.github.com/velotiotech/4bc4f113b85e4d7bd1f6658bb33213e0.js

Voila! Your API service is ready. Fire up your server, and then use Postman to make requests to your API and see the magic happen. 

You can also add other API services for fetching a user by ID, deleting a user, creating a user, and updating a user. I will not discuss them here to keep this blog short. You can find these in the Github repository I mentioned in the beginning.

Deploying your Server to Production

What we have been doing has been in the development phase. Now, we need to take this to production. You just need to have a <project-root>/build.js </project-root>script that will create a <project-root>/dist</project-root> folder and transpile all the TypeScript files that you have written. It can look like this: 

CODE: https://gist.github.com/velotiotech/f7ea28602aec64ce1e6cc9b708684898.js

Then, add this line to your <project-root>/package.json</project-root>:

CODE: https://gist.github.com/velotiotech/4cb9e391cd4671852c7660622bfe9354.js

Now, you can use:

CODE: https://gist.github.com/velotiotech/dee984ea753cb9367af0a1166f19d518.js

Doing so builds up the <project-root>/dist</project-root> folder and transpiles your code. You can deploy this folder to your deployment environment and run it to start your production server:

CODE: https://gist.github.com/velotiotech/50b324fa292b177411294c650fbe94e8.js

Note: You will need to do some additional setting up of your Nginx or AWS Virtual Machine to complete your deployment, which is beyond the scope of this blog.

Going Forward

Congratulations. You have made it through this tutorial that guided you through the process of setting up a web server. But this is just the beginning, and there is no end to the improvements and optimizations that you can add to your server to make it better and sturdier. And you will continue to discover them in your journey of developing your web application. Some of the key points that I want to mention are:

Managing Environments

Your Web server will be operated in multiple environments, such as development, testing, and production. Some of the vital configurations like AWS credentials and DB passwords are sensitive information, and managing them per environment is key to your development and deployment cycle. I strongly recommend using libraries like Dotenv and keeping your env configurations separate in your codebase. You can look up typescript-express-server for this.

Configuring Swagger

Software developers nowadays swear by this tool. It’s proved to be a godsend for API documentation and keeping APIs in confirmation with the OpenAPI standard. On top of that, it also does API requests validation according to your API specifications. I strongly recommend you configure this in your web server.

Writing Tests

Writing API tests and unit tests can be a crucial part of web application development as it exposes possible gaps in your systems. You can use Superagent, the lightweight REST API, to test your APIs for all possible requests and response scenarios. Please look up the src/spec in typescript-express-server about how to use it. You can also use Postman for API Testing Automation. For most of the services that you write, you should make sure to add unit tests for each of those using Jest.

Further Reading

  1. Node.js production checklist
  2. Node.js production best practices
  3. Production best practices: performance and reliability
Get the latest engineering blogs delivered straight to your inbox.
No spam. Only expert insights.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Did you like the blog? If yes, we're sure you'll also like to work with the people who write them - our best-in-class engineering team.

We're looking for talented developers who are passionate about new emerging technologies. If that's you, get in touch with us.

Explore current openings

Set Up A Production-ready REST API Server Using TypeScript, Express And PostgreSQL

Introduction

So, you have a brilliant idea for a web application. It’s going to be the next big thing, and you are super-excited about it. Maybe you have already started building the perfect React/Angular UI for your app.

Eventually, you realize that, like most web apps, your app is going to be data-intensive and will need a lightning-fast web server. You know that Node.js is the de facto standard for web servers for how well it unifies front-end and back-end web development with JavaScript, so you go for it.

But you want your server to be robust and reliable too. A colleague introduces you to TypeScript, the superset of JavaScript developed by Microsoft, and recommends it for its strict static typing and compilation.

Now comes storing the data. Naturally, you select PostgreSQL. After all, it is the most advanced Relational Database Management System (RDBMS) in the world, with its object-oriented features and extensibility. But RDBMSs can be slow for frequently used data and caching, so you decide to add Redis, the in-memory cache, to decrease data access latency and ease the load off your relational data store.

That’s it. You have a perfect server waiting to be built. And while the initial process of getting it up and running can get arduous, you have come to the right place. This blog is going to guide you through the initial setup process.

Prerequisites

I am assuming you have a non-root user with sudo privileges running on Ubuntu 16.04. Before we start, please make sure you have the following: 

  1. NPM (~v6.9.0) and Node.js (~v10.16.0) – You can use this How to Install Node.js on Ubuntu 16.04
  2. Redis – How to install Redis on Ubuntu 16.04
  3. PostgreSQL – How to install PostgreSQL on Ubuntu 16.04

Of course, MacOS or Windows would do fine too for this tutorial, but to use them, please find appropriate installation guides on the Internet before moving forward. 

If you don’t want to go through the steps below, you can check out my GitHub Repo typescript-express-server and use it as your application skeleton. It has been set up with default configurations, which you can change later. Nevertheless, I strongly recommend going through this guide to further your understanding of the project files and configuration nuances.

Initializing Server (Express with TypeScript)

Setting up an Express Application with TypeScript can be done in three steps: 

Initialize project using NPM

Create a folder and run:

CODE: https://gist.github.com/velotiotech/369a5af8ce82844f64720375849c8c62.js

This will ask you a couple of project-specific questions, like name and version, and will create a package.json file, which may look like this:

CODE: https://gist.github.com/velotiotech/064b8e3cd35c2102c6e1f8efb0e7ea55.js

This manifest file will contain all the metadata of your project, like module dependencies, configs, and scripts. For more information, check out this very good read about the basics of package.json

Setting up TypeScript Configuration (tsconfig.json)

This file needs to be created in the root of a TypeScript project. During development, TypeScript provides us with the convenience of running the code directly from the .ts extension files. But during production, since Node.js only understands JS, the entire TS files need to be transpiled to JS. Some of the options are: include - specifies the files to be included, exclude -  the files to exclude, and the compiler options: outFIle and moduleResolution.

First, we need to install some TypeScript specific modules: 

CODE: https://gist.github.com/velotiotech/95b021f1728a9b8a61d9fca89b0b9e59.js

This is the tsconfig.json file with some default configurations:

CODE: https://gist.github.com/velotiotech/2cd42f3db972ebcf47d1819a80870826.j

For a detailed reference, checkout tsconfig.json.

Setting up ESLint

It is not mandatory to use this JavaScript linter, but it’s highly recommended for enforcing code standards and keeping code clean. TypeScript projects once used TSLint, but it has been deprecated in favor of ESLint.

Run this command:

CODE: https://gist.github.com/velotiotech/6b28a79d034c285a74e445e10e758649.js

Create a .eslintrc file in the project root and use the following starter configuration:

CODE: https://gist.github.com/velotiotech/9f2c1079a009c1453f9a8960317cbcea.js

Lastly, add a lint script to package.json:

CODE: https://gist.github.com/velotiotech/5a4418e83d308ea014c7e2a309cae988.js

Now, you can run the command below to lint your codebase for lint errors:

CODE: https://gist.github.com/velotiotech/b53b6acd21f1279c1711b9e6cfa38886.js

ESLint has ample rules to enforce standards in your code. Please look them up at Eslint with TypeScript.

Express App

Finally, we need to install Express, which is as simple as running this command:

CODE: https://gist.github.com/velotiotech/3935d682c9df4c5c2ae4d31846fec77c.js

You need a server file (src/Server.ts), which you can create like this:

CODE: https://gist.github.com/velotiotech/c449d81e54b81df7136b3076698efaa5.js

You will also need src/index.ts that will be the entry point for your application:

CODE: https://gist.github.com/velotiotech/4f1412ba1d345b90e6b7b95bf255ae6d.js

Error Handling

Many Express servers are configured to swallow all errors by configuring an Uncaught Exception handler, which in my opinion, is bad news. The best thing to do is to allow the application to crash and restart. Uncaught Exceptions in Node.js is a good read regarding this.

Nonetheless, we are going to configure an error handler that will print errors and send a BadRequest response when an invalid HTTP request comes your API’s way.

In the src/Server.ts, add this:

CODE: https://gist.github.com/velotiotech/bd1fbae64c7afc03ba3bebe8cf9a5f80.js

Kudos! You have a basic Express server set up. Fire it up by running:

CODE: https://gist.github.com/velotiotech/a60fb319af122a67ddaf0e5f56af5d80.js

Connecting with the Database Store using TypeORM

We have a basic server ready to go, but we need to connect it to our Postgres database using an ORM. TypeORM is a versatile ORM that supports both Active Record and Data Mapper patterns, unlike all other JavaScript ORMs. It can be installed on our server with the following steps:

CODE: https://gist.github.com/velotiotech/5d84d636b9d05c7a228a27d7e7434007.js

Create an ormconfig.json file in your project root with the following configuration:

CODE: https://gist.github.com/velotiotech/e6be0ec23cd6f81c8e5aed073a28ef2d.js

Create a src/db.ts file that will initialize the database connection:

CODE: https://gist.github.com/velotiotech/3d03479ced145cf8564f05026b9765b7.js

TypeORM Entities are classes that represent the data models in our application. We are going to build a User Entity (which application doesn’t have a user, duh!) like this in src/entities/User.ts:

CODE: https://gist.github.com/velotiotech/8589621bfc50305384a8cebbc2b3cbf5.js

Then, add these lines to src/index.ts:

CODE: https://gist.github.com/velotiotech/64af3251f7be465e2c4191c04a0ea6bd.js

You will need the env variables, like TYPEORM_CONNECTION, TYPEORM_HOST, and TYPEORM_USERNAME, with your postgres db’s connection params. Please check TypeORMs documentation for more details. 

Connecting Redis

We will use Tedis, the TypeScript wrapper for Redis in our server:

CODE: https://gist.github.com/velotiotech/ffe2783746d10c08ad19ed0796aa36a3.js

Add these lines to src/db.ts:

CODE: https://gist.github.com/velotiotech/2fb96749e512dcb9bd0b4aec2d906123.js

And these lines to src/index.ts:

CODE: https://gist.github.com/velotiotech/3ef02579bcd706e77ea63273c8f1aa99.js

Now, your application code can use the Redis cache using the client created above.

Configuring Logging

Logging is pivotal to an application because it gives us a real-time view of the state of our application. For development, we are going to install the Morgan Request Logger, a library that logs HTTP requests params. It comes really handy for debugging. 

CODE: https://gist.github.com/velotiotech/fbdfd5ccbfb758e4beaed76bf1e66087.js

And include this in src/Server.ts:

CODE: https://gist.github.com/velotiotech/9c9bbe24abf1577e44e6bd20037964ce.js

Winston can be used as the system-wide universal logger. Install it like this:

CODE: https://gist.github.com/velotiotech/abcf76b716f808efe27c421656353bf1.js

Then, add a src/shared/Logger.js file:

CODE: https://gist.github.com/velotiotech/14686ff164b30c5f92fe52fdca5346eb.js

Now, you can use this logger from anywhere in the code, be it for error logging in your API methods or for debugging purposes:

CODE: https://gist.github.com/velotiotech/87eaa841ccb46c05e597172399578ad3.js

Creating your First API Service

This is the moment you have been waiting for: creating your first API service for your application, the crux of the functionality that will define your web application.

This API service is a simple GET request handler, which returns all the users in your database. You should have src/Users.ts, which can look like:

CODE: https://gist.github.com/velotiotech/70145d85814521f2343af6b59db45634.js

Add src/routes/index.ts

CODE: https://gist.github.com/velotiotech/4bc4f113b85e4d7bd1f6658bb33213e0.js

Voila! Your API service is ready. Fire up your server, and then use Postman to make requests to your API and see the magic happen. 

You can also add other API services for fetching a user by ID, deleting a user, creating a user, and updating a user. I will not discuss them here to keep this blog short. You can find these in the Github repository I mentioned in the beginning.

Deploying your Server to Production

What we have been doing has been in the development phase. Now, we need to take this to production. You just need to have a <project-root>/build.js </project-root>script that will create a <project-root>/dist</project-root> folder and transpile all the TypeScript files that you have written. It can look like this: 

CODE: https://gist.github.com/velotiotech/f7ea28602aec64ce1e6cc9b708684898.js

Then, add this line to your <project-root>/package.json</project-root>:

CODE: https://gist.github.com/velotiotech/4cb9e391cd4671852c7660622bfe9354.js

Now, you can use:

CODE: https://gist.github.com/velotiotech/dee984ea753cb9367af0a1166f19d518.js

Doing so builds up the <project-root>/dist</project-root> folder and transpiles your code. You can deploy this folder to your deployment environment and run it to start your production server:

CODE: https://gist.github.com/velotiotech/50b324fa292b177411294c650fbe94e8.js

Note: You will need to do some additional setting up of your Nginx or AWS Virtual Machine to complete your deployment, which is beyond the scope of this blog.

Going Forward

Congratulations. You have made it through this tutorial that guided you through the process of setting up a web server. But this is just the beginning, and there is no end to the improvements and optimizations that you can add to your server to make it better and sturdier. And you will continue to discover them in your journey of developing your web application. Some of the key points that I want to mention are:

Managing Environments

Your Web server will be operated in multiple environments, such as development, testing, and production. Some of the vital configurations like AWS credentials and DB passwords are sensitive information, and managing them per environment is key to your development and deployment cycle. I strongly recommend using libraries like Dotenv and keeping your env configurations separate in your codebase. You can look up typescript-express-server for this.

Configuring Swagger

Software developers nowadays swear by this tool. It’s proved to be a godsend for API documentation and keeping APIs in confirmation with the OpenAPI standard. On top of that, it also does API requests validation according to your API specifications. I strongly recommend you configure this in your web server.

Writing Tests

Writing API tests and unit tests can be a crucial part of web application development as it exposes possible gaps in your systems. You can use Superagent, the lightweight REST API, to test your APIs for all possible requests and response scenarios. Please look up the src/spec in typescript-express-server about how to use it. You can also use Postman for API Testing Automation. For most of the services that you write, you should make sure to add unit tests for each of those using Jest.

Further Reading

  1. Node.js production checklist
  2. Node.js production best practices
  3. Production best practices: performance and reliability

Did you like the blog? If yes, we're sure you'll also like to work with the people who write them - our best-in-class engineering team.

We're looking for talented developers who are passionate about new emerging technologies. If that's you, get in touch with us.

Explore current openings