DEV Community

Cover image for Setup a Node Express API with TypeScript (2021)
Royce Chua
Royce Chua

Posted on • Updated on

Setup a Node Express API with TypeScript (2021)

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

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

  "scripts": {
    "start:dev": "ts-node-dev ./index.ts",
    "start": "tsc && node ./lib/index.js",
  },
Enter fullscreen mode Exit fullscreen mode

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

mkdir node-express-typescript-starter && npm init 
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

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

npx tsc --init
Enter fullscreen mode Exit fullscreen mode

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

  "scripts": {
    "start": "ts-node-dev ./index.ts"
  },
Enter fullscreen mode Exit fullscreen mode

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:

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}`);
}

Enter fullscreen mode Exit fullscreen mode

6. Run the code

To run the Node express API simply run the command

npm run start
Enter fullscreen mode Exit fullscreen mode

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

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

Top comments (6)

Collapse
 
mhm13dev profile image
Mubashir Hassan

Thank you for an easy guide!

Collapse
 
jimmythecode profile image
James

I get the following in my console when I try to run the code:
Error: Debug Failure. False expression: Non-string value passed to ts.resolveTypeReferenceDirective, likely by a wrapping package working with an outdated resolveTypeReferenceDirectives signature. This is probably not a problem in TS itself.

I'm on a Windows machine. Not sure that's relevant.

Collapse
 
theprogrammer21 profile image
Lukas Windisch

Unfortunately my environment doesn't recognize the express.json() function.

Property 'json' does not exist on type 'Express'.

This happens when I execute the exact same code.

Collapse
 
airor4 profile image
Airor4

I made an account just to try and answer your question. Certain versions of Express have bodyParser bundled in with it. If .json() is not working for you you can npm i bodyParser and use that instead. See: stackoverflow.com/questions/472321...

Collapse
 
theprogrammer21 profile image
Lukas Windisch

Thank you a lot for doing that!
In fact I just had an old version of the @types/express package where the json() function has not existed yet.

Collapse
 
ahmadmazaal profile image
AhmadMazaal • Edited

Very detailed and professional totural, thank you!