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 --save2npm 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.
1{2 "compilerOptions": {3 "target": "es6",4 "module": "commonjs",5 "allowJs": true,6 "outDir": "./build",7 "rootDir": "./src",8 "esModuleInterop": true9 }10}
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";23const app: Application = express();45app.use(express.json());67app.get("/", (req: Request, res: Response): object => {8 return res.json({ status: "success", message: "Welcome to API Service" });9 }10);1112app.use((req: Request, res: Response, next: NextFunction) => {13 const error = new Error("Route Not found");14 next(error);15});1617app.use((error: { message: string; status: number }, req: Request, res: Response,next: NextFunction18 ) => {19 res.status(error.status || 500);20 res.json({21 status: "error",22 message: error.message23 });24 next();25 }26);2728const PORT: any = process.env.PORT || 3000;2930app.listen(PORT, () => console.log(`app listening on port ${PORT}`));
At this point, your project structure should look like the image below.
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.