Navigate back to the homepage

Setting Up Node API with Typescript

Ezekiel Ekunola
August 13th, 2019 · 1 min read

I’ll be taking us through the steps of setting up a basic Node API with typescript.

Note: You should have Nodejs installed on your machine.

First thing is to create our project folder and initialize it with npm to generate the package.json file.

1npm init -y

Install dependencies

1npm i express --save
2npm i @types/node @types/express ts-node typescript nodemon --save-dev

Create a tsconfig.json file in the root of your application or run npx tsc --init on your terminal and add the configuration below.

2 "compilerOptions": {
3 "target": "es6",
4 "module": "commonjs",
5 "allowJs": true,
6 "outDir": "./build",
7 "rootDir": "./src",
8 "esModuleInterop": true
9 }

Note: More options can be added to the tsconfig.json file. Find out more here.

Add scripts to package.json file.

1"scripts": {
2 "dev": "nodemon src/app.ts",
3 "start": "tsc && node build/app"
4 }

Create a src directory where our application would be built. Inside the src directory, create an app.ts file.

Inside the app.ts file, add the code below.

1import express, { Application, Request, Response, NextFunction } from "express";
3const app: Application = express();
7app.get("/", (req: Request, res: Response): object => {
8 return res.json({ status: "success", message: "Welcome to API Service" });
9 }
12app.use((req: Request, res: Response, next: NextFunction) => {
13 const error = new Error("Route Not found");
14 next(error);
17app.use((error: { message: string; status: number }, req: Request, res: Response,next: NextFunction
18 ) => {
19 res.status(error.status || 500);
20 res.json({
21 status: "error",
22 message: error.message
23 });
24 next();
25 }
28const PORT: any = process.env.PORT || 3000;
30app.listen(PORT, () => console.log(`app listening on port ${PORT}`));

At this point, your project structure should look like the image below.

Project Structure

Development 👨🏾‍💻

To run the application on the development environment, run the command below

1npm run dev

Note: The above command compiles the files found in the src directory in memory.

Production 🚀

To run the application on the production environment, run the command below

1npm start

Note: The above command compiles the files found in the src directory to a build directory and runs the app.js file in the build directory, as specified above in the start script in our package.json file.

The project used in this article can be found here.

If you have any questions or feedback, please feel free to reach out on Twitter.

Thanks for reading.

More articles from easybuoy

Deploying Node App to Heroku

Learn about deploying a node app to heroku.

July 4th, 2019 · 2 min read

Deploying React App from Github to Netlify

Learn about deploying react app to netlify.

July 4th, 2019 · 1 min read
© 2018–2020 easybuoy
Link to $ to $ to $ to $