Create Server using Express and TypeScript
Tags: react, node, express, typescript
Published: 2021-05-27 04:46:09

![Express_TS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/98vfat7f9vpzjaveu2gg.png)

In this post, we will learn how to create a server using [Express](https://expressjs.com/) and [TypeScript](https://www.typescriptlang.org/)

> If you are feeling lucky, refer to this [commit](https://github.com/achukka/tdsvc/commit/c9c973a063ca86721822a622294b3439efe2ff0b) for full code

**Step 1:** Setting up the project

- Download and install the latest stable version of [Node](https://nodejs.org/en/download/)
- At the time of writing this post, the recommended version is `14.17.0`
```json
$ node --version
v14.17.0
```
- Create a new directory for the service
```json
mkdir tdsvc
```
- Initialize a node application
```json
cd tdsvc
npm init
```
- Fill out the necessary project details to generate a  `package.json`
- Set main to `dist/index.js`
- Add start script in the scripts section
```json
"start": "tsc && node dist/index.js"
```
- Add `"type": "module"` to enable ES5 modules

> See [this](https://nodejs.org/docs/latest-v13.x/api/esm.html#esm_enabling) post for more information

Stitching all the above your `package.json` should look something similar to this 
```json
{
  "name": "tdsvc",
  "version": "0.1.0",
  "description": "A Node Server to maitain todolist",
  "main": "dist/index.js",
  "type": "module",
  "scripts": {
    "start": "tsc && node dist/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/achukka/tdsvc.git"
  },
  "keywords": [
    "node"
  ],
  "author": "Aditya Chukka",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/achukka/tdsvc/issues"
  },
  "homepage": "https://github.com/achukka/tdsvc#readme",
  "devDependencies": {
    "@types/express": "^4.17.12",
    "typescript": "^4.3.2"
  },
  "dependencies": {
    "express": "^4.17.1"
  }
}
```


**Step 2:** Installing dependencies 

- Install `typescript` locally
```bash
npm install --save-dev typescript
```
- Install `Express` framework 
```bash
npm install --save express
```
- Install types for Express locally
```bash
npm install --save-dev @types/express
```
- Set TypeScript compiler options through `tsconfig.json`
```json
{
  "compilerOptions": {
    "module": "ESNext",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist"
  },
  "lib": ["esnext"]
}
```
- Let's go over some of the options above
    - With `esModuleInterop` we can import CommonJS modules in compliance with es6 modules.
    - As the name suggest, we use `outDir` to specify all the output directory for all transpiled (`.js`) files. In this post we are settings it to _dist_
    - `sourceMap` allows debuggers to display the actual TypeScript file
    - `target` specifies the output language level

    > You can read more about tsconfig in tyescript [docs](https://www.typescriptlang.org/tsconfig)



**Step 3:** Create a basic server

- Create an empty `index.ts` in src directory
```bash
mkdir src
touch src/index.ts
```
- Create an Express application in `src/index.ts`
```javascript
import express from "express";

const app = express();
```
- Add a sample port to listen on (Example: 3000)
```javascript
const port = 3000;
```
- Add a HTTP [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) method
```javascript
app.get("/", (req, res) => {
  res.send("You are listening from express server");
});
```
- Listen for requests on `port`
```javascript
app.listen(port, (err?) => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});
```

Stitching all sections together we get
```javascript
import express from "express";

const app = express();
const port = 3000;
app.get("/", (req, res) => {
  res.send("You are listening from express server");
});

app.listen(port, (err?) => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});
```

**Step 4:** Running the server

- You can run your server by `npm start`
- If the above command runs successfully, you should a message in your terminal

```bash
> tsc && node dist/index.js

server is listening on 3000
```
- Visit http://localhost:3000 in your browser and you should see something similar

![Server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bo323g1mkm4y16fnyqx8.PNG)

Please find the entire code in this [commit](https://github.com/achukka/tdsvc/commit/c9c973a063ca86721822a622294b3439efe2ff0b)

❤️ Congratulations 👏, you have successfully created a server using Express and TypeScript

Thanks for reading through the entire article. Please reach out with questions, comments and/or feedback.