API Server Setup with Express.js and TypeScript

Part 1: How to setup basic Express API server

Ward Price
JavaScript in Plain English

--

This will be a quick run through how to setup basic Express API server.

Go ahead and create a new directory and open it in your IDE. Initiate the project with npm with the following command

$ npm init -y

This will setup your package.json file with all the default values. If you wish to go through the prompt to fill out all the fields manually just remove the -y flag.

Alright lets get to work. First, lets install express.

$ npm i express 

Since we are using TypeScript lets add it to the project as well as the types for express and Nodejs and a TypeScript compiler for node but this time we will throw the-D flag as we will only need these packages development.

$ npm i -D @types/express @types/node typescript ts-node

Now lets initialize typescript to be used in our project

$ npx tsc --init

A new file will be created named tsconfig.json. Since TypeScript it is here you can set what version of JavaScript you want your typescript to be compiled to as well as how strict you want the type checking to be. For a detailed explanation check out the tsconfig docs.

Next, open the package.json file in your IDE. You should see a key "main" and it’s value is index.js. Since we are using TypeScript lets set that to index.ts. You should also see a key "scripts" and inside its value is a key of "test". Add a comma to the end of the value of "test" and add a new key "start" and set that equal to “ts-node ./src/index.ts”. This way when we type npm start in the terminal it will run our app for us.

This isn’t neccessary but more of a preference. I normally have nodemon installed to auto run my code whenever a change happens and have grown accustomed to using npm start to run my code. We will add nodemon to this app in a future part of this tutorial series.

Besides version differences your package.json should look similar to this.

Importing Express

Now we are ready to start building. Create a folder named src and inside that folder a file named index.ts.

This file is what will load first. It will connect to the database and send the request to the router which will then send the request to the appropriate controller.

import express from 'express'

We’ve got express imported but we are not using it yet. Create a constant named app and set it equal to express().

const app = express()

Side note: I have seen some express with typescript examples explicitly declare what type app is and you can do this easily by importing the Application type when you import express with the following line.

import express, { Application } from 'express'

Now when you declare the app constant from the express function you’d simply write.

const app: Application = express()

Some people explicitly declare EVERYTHING in their typescript files but my approach is to import types if they are not already included in the package and only explicitly declare a type when the typescript linter yells at me. The advantage is the tooling that is available through vscode. Typescript knows what everything that is declared is, so therefore the intellisense is even MORE helpful than with javascript

Setting up Express to listen at a port

Lets create the port our server will listen at by creating another constant named port and set it equal an unused port on our system. I’ll use the port 3000.

const port = 5000

To tell express to listen to this port is very simple. We utilize the listen method and enter two parameters, the port variable and an anonymous function which calls console.log to

app.listen(port, () => {
console.log(`Server is listening on port ${port}`)

If you run the command npm start in your terminal it will start up the app and you will see the output of Server is listening on port 3000.

Hello World endpoint

Now lets test if we can navigate to the server via Postman or our browser and get a response. Again, Express makes this easy on us.

app.get('/', (req, res) => {
res.send('Hello World')
})

We place this inbetween the app.listen function and the the two constants we made. If the express receives a get request on the base url, in our case http://localhost:3000/ the server will send the string of "Hello World!" back to the user.

As above with the Application type, we can import the types for req and res if we wanted to explictly declare them with the following import…

import express, { Request, Response } from 'express'

…and implementation. But to truly be explicit in our declaration of the app.get() function we need to declare the return type of the function. In this case because we actually don’t return anything but pass the data onto the res variable. The return type is void.

app.get('/', (req: Request, res: Response): void => {
res.send('Hello World')
})

Again, we don’t HAVE to be this explicit because we already imported the express data types. However, if you prefer it, knock yourself out!

With this we have a very very basic Express server setup. You might be wondering “Well this looks just like JavaScript? I thought this was supposed to TypeScript?” Because we imported the types we are going to use TypeScript was able to figure what the types are of everything! TypeScript is in the background looking over all our code to make sure the types are correct so we can rest assured that our code will work and a lot of the lazy errors we make aren’t there. It’s also what is allowing us to the ES modules import instead of using require.

We are able to write more modern code as well as being able to rest easy that our code will run!

Stay tuned for the next update. We will add more functionality.

Tutorials in Series

Part 1: “Hello World!”

Part 2: Setting Up The Router

Part 3: Connecting to MongoDB

--

--