Setup a Node Express API with TypeScript (2021)
Tags: node, express, typescript
Published: 2021-03-29 15:46:22

This tutorial will help you quickly setup a Node express API with TypeScript. 

All the steps done here can be cloned through my Github repository [https://github.com/roycechua23/node-express-typescript-starter](https://github.com/roycechua23/node-express-typescript-starter)

**Important note for production:** This blog is meant to make developer life more straightforward. As such, we're focusing on initial setup and not for a production build. For production builds, you still need to transpile to JS using tsc  

``` json
  "scripts": {
    "start:dev": "ts-node-dev ./index.ts",
    "start": "tsc && node ./lib/index.js",
  },
``` 

Note that, lib can be replaced with dist or whatever your "outputDir" is on the TypeScript configuration file (tsconfig.json) that we'll also be going over later in this blog. 

## 1. Pre-requisites
For this blog you need to have Node.js(v10+) installed on your machine for this to work without any issues.

## Create initial folder and package.json
Open your terminal and create your folder and package.json using

``` bash
mkdir node-express-typescript-starter && npm init 
```

Fill out all the information being asked. Set the entry point to index.ts and feel free to provide the other information with appropriate values.

## 2. Install the dependencies
You need to install the following dependencies using npm 
``` bash
npm install typescript --save-dev
npm install ts-node-dev --save-dev
npm install express 
npm install @types/express --save-dev
npm install @types/node --save-dev
```
This is only for a minimal setup. The **ts-node-dev** dependency will continuously recompile and run the .ts file directly instead of compiling the .ts file then running .js file. It will be our replacement for nodemon which is only for .js files.

## 3. Create a tsconfig.json file 
You can create a TypeScript configuration file using the command
``` bash
npx tsc --init
```
This will automatically create a tsconfig.json for you with the default settings (you can change them anytime you want).

## 4. Modify the scripts in package.json 
Using your code editor or IDE, modify the *scripts:* in package.json to include the keyword and value as shown below
``` json
  "scripts": {
    "start": "ts-node-dev ./index.ts"
  },
``` 
You can remove the test key for now.

## 5. Create the index.ts file 
Create the index.ts file using your code editor and copy and paste the sample code:

``` typescript
import express, { Application, Request, Response } from "express";

const app: Application = express();
const port = 3000;

// Body parsing Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get(
	"/",
	async (req: Request, res: Response): Promise<Response> => {
		return res.status(200).send({
			message: "Hello World!",
		});
	}
);

try {
	app.listen(port, (): void => {
		console.log(`Connected successfully on port ${port}`);
	});
} catch (error) {
	console.error(`Error occured: ${error.message}`);
}

```

## 6. Run the code 
To run the Node express API simply run the command 
``` bash
npm run start
```
It should now display the message **"Connected successfully on port 3000"** on the console. 

If you encounter an error **"Error: listen EADDRINUSE: address already in use :::3000"**, this means that you have other services currently running on port 3000 (ex. React Apps, other Node.js Apps, etc..)

Test this out by either opening your browser or Postman with a GET Request to **localhost:3000**.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cs94snlmh0hyt8tegiv6.png)

## 6. Try modifying the code 
Try modifying the the return message "Hello World!" to any message you like. It should automatically restart the node server and you can try it out again to see the changes.

Congratulations, you have now successfully setup your Node Express API with TypeScript without doing any additional complex task.

Your support would be very much appreciated by reacting to this post. Buying me a coffee would mean a lot
https://www.buymeacoffee.com/royce.chua