Express with TypeScript and TypeOrm. Part 1
Tags: typescript, node, javascript
Published: 2020-04-25 11:15:53

<!----- Conversion time: 0.568 seconds.


Using this Markdown file:

1. Cut and paste this output into your source file.
2. See the notes and action items below regarding this conversion run.
3. Check the rendered output (headings, lists, code blocks, tables) for proper
   formatting and use a linkchecker before you publish this page.

Conversion notes:

* Docs to Markdown version 1.0β22
* Sat Apr 25 2020 04:13:09 GMT-0700 (PDT)
* Source doc: Express with TypeScript and TypeOrm. Part 1
* Tables are currently converted to HTML tables.
----->


Setting up an express server with TypeScript can be daunting at first. In the first part of this 2-part series, we will look at how to set up a professional express TypeScript project from scratch. We will set up the base folder structure and also the base express setup. We will then look at how to connect to our database(PostgreSQL) in this case in the second part. Let's begin.

To set up an express project you need to have nodeJS installed locally on your machine, this can be downloaded from [here](https://nodejs.org). This also gives you access to a very important CLI tool called NPM (Node Package Manager). Using NPM we can add packages from the NPM registry into our project.

Verify that NodeJS is installed on your machine by typing


```
node --version
```


A version should be printed indicating NodeJS is successfully installed on your computer.

We create an empty directory that will hold all of our project’s code. I’m going to name mine express-typescript but feel free to use whichever name you want.


```
mkdir express-typescript && cd express-typescript
```


Inside this folder, we initialize a new npm project by typing 


```
npm init -y
```


The -y flag is to tell NPM to give us the default configuration. We then install express as well as the types for express and the typescript compiler along with other helper libraries.


```
npm install --save express 
npm install --save-dev @types/node @types/express typescript nodemon ts-node
```


Typescript is what helps our application transpile the typescript programming language into JavaScript. Ts-node allows us to run typescript files directly without having to transpile them first, this is great for development mode. Nodemon automatically watches for changes within our project and restarts the server without having to do that manually.

Next off, we’ll create a tsconfig.json file to tell the typescript compiler how to compile our code. We add the following options into the tsconfig.json file


```
{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "sourceMap": true,
    "outDir": "./dist",
    "removeComments": true,
    "moduleResolution": "node",
    "noImplicitAny": false,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,

    //add decorator support
    "allowSyntheticDefaultImports": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "include": ["./src/**/*.tsx", "./src/**/*.ts"],
  "exclude": ["node_modules"]
}
```


We modify our package.json with the following code


```
{
  "name": "express-typescript",
  "version": "1.0.0",
  "description": "Typescript with express tutorial",
  "main": "index.ts",
  "author": "Francis Gyimah <fgyimah883@gmail.com>",
  "license": "MIT",
  "private": false,
  "scripts": {
    "start": "node ./dist/index.js",
    "start:dev": "nodemon",
    "build": "tsc"
  },
  "dependencies": {
    "express": "^4.17.1",
  },
  "devDependencies": {
    "@types/express": "^4.17.6",
    "@types/node": "^13.13.0",
    "nodemon": "^2.0.3",
    "ts-node": "^8.8.2",
    "typescript": "^3.8.3"
  }
}
```


We have included 3 scripts into our server and these are:



*   start: This is to tell how we want to start our server in production mode, the compiled javascript will be in the dist folder and we are telling node to run our javascript file from there
*   start:dev: This is how we start our development server, by default, nodemon will look for a file called nodemon.json to run whenever this command is called. We’ll create that in the next step
*   build: this is how we build or transpile our TypeScript code into JavaScript using the tsc command, which we get as a result of installing the typescript dependency.

To configure nodemon we create another file in the root directory of our project called nodemon.json, and add the following code to it


```
{
  "watch": ["./src/**/*", ".env"],
  "ext": "ts",
  "exec": "ts-node ./src/index.ts"
}
```


This tells nodemon to watch for changes in the src directory, where our actual code is going to live and also watch the .env file, which is a special file where all our sensitive information like API keys is going to live. We also watch all files with the .ts extension, meaning all typescript files in the src folder. The exec tells nodemon the command to run which is ts-node command and our main script is the index.ts file inside the src folder.

We create the src folder and the index.ts file in it

We create a base express server using the following code snippet


```
import * as express from 'express';

const app = express();

//configure application routes
//@GET - dummy api route
//@ts-ignore
app.get('/api', (req, res, next) => {
  res.status(200).json({
    hello: 'World!',
  });
});

const port: Number = Number(process.env.PORT) || 3000;
const startServer = async () => {
  await app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`);
  });
};

startServer();
```


That’s it, we now run the following command in the terminal


```
npm run start:dev
```


and go to [https://localhost:3000/api](https://localhost:3000/api) to see our result. 

In the next part, we’ll look at configuring environment variables and how to connect to a PostgreSQL database  using [typeOrm](https://typeorm.io)


<!-- Docs to Markdown version 1.0β22 -->