NodeJS and Typescript Setup for REST API - Part 1
In this article we will cover the following topics for NodeJS and Typescript Setup for REST API - Part 1
Introduction
In this article, we will learn how to setup NodeJS and Typescript for REST API. I am assuming that you already have basic knowledge of REST API and NodeJS.
- We are going to use ExpressJS framework along with Prisma ORM for database operations.
- You can use any ORM or raw
databaseoperations if you want. - We will going to use NodeJS version 20.7.0 or above (assuming you have it installed).
Installing Dependencies
To get started, We need to initialize a new NodeJS project. Let’s do that first by running following command:
npm init -y
This will create a package.json file in the root of the project. Now we need to install some dev dependencies.
npm install -D typescript @types/node @types/express ts-node prisma nodemon
By running this command, we are installing following dependencies:
typescript: TypeScript compiler.@types/node: TypeScript definitions for Node.js.@types/express: TypeScript definitions for Express.ts-node: TypeScript execution environment for Node.js.prisma: Prisma ORM.nodemon: To run the server in development mode.
Now, we will install actual dependencies.
npm install express @prisma/client cors morgan express-validator lodash.merge dotenv
By running this command, we are installing following dependencies:
express: ExpressJS framework.@prisma/client: Prisma client.cors: To handle Cross-Origin Resource Sharing.morgan: To log HTTP requests.express-validator: To validate request data.lodash.merge: To merge objects.dotenv: To load environment variables from.envfile.
Typescript and Environment Variables Setup
We need to create 2 files tsconfig.json and .env. You can use following command to create them:
touch tsconfig.json .env
Now we will define some environment variables in .env file.
PORT= // Port number for the server
DATABASE_URL= // Database URL
Now we need to create a folder src and inside that folder create a file index.ts. This is where we will write our code.
mkdir src && touch src/index.ts
for now let just write Hello World in index.ts file.
console.log('Hello World');
Now we need to configure tsconfig.json file. This file is used to tell TypeScript compiler how to compile the code.
{
"compilerOptions": {
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": false,
"lib": ["esnext"],
"esModuleInterop": true,
"declaration": true
},
"include": ["src/**/*.ts"]
}
We are defining following options in tsconfig.json file:
compilerOptions: Defines compiler options .sourceMap: To generate source maps.outDir: Output directory for the compiled code.rootDir: Root directory for the source code.strict: Enable all strict type-checking options.lib: Specify the built-in library files to include. (We are includingesnextlibrary which contains latest ECMAScript features)esModuleInterop: Enable compatibility with CommonJS modules.declaration: Generate declaration files.
include: Specify the files to include in the compilation.
Define below script in package.json file to compile the code.
"scripts": {
"dev": "nodemon src/index.ts",
"build": "tsc -p tsconfig.json",
"start": "node dist/index.js"
},
Prisma Setup
Now we need to setup Prisma. First, we need to initialize Prisma in our project. We can do that by running following command:
npx prisma init
This will create prisma folder in the root of the project with schema.prisma file.
We are going to use MongoDB as our database. So, make sure you have working MongoDB DATABASE_URL in .env file. Here is the schema.prisma file with User model:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
email String @unique
name String
}
Tip: You can run
npx prisma formatto format theschema.prismafile.
Now we need to generate Prisma client which will be used to interact with the database in our code. We can do that by running following command:
npx prisma generate
For the next step, we need to create a db.ts file in src folder. This file will be used to connect to the database and will export a Prisma client. Here is the db.ts file:
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export default prisma;
Server Setup
In order to setup the server, we need to create 2 files server.ts and router.ts in src folder.
Here is how our router.ts file will look like with a simple route:
import { Router } from "express";
const router = Router();
router.get("/", (req, res) => {
res.send("Hello World");
});
export default router;
Here is how our server.ts file will look like with a router attached for /api route:
import express from "express";
import router from "./router";
import morgan from "morgan";
import cors from "cors";
const app = express();
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/api", router);
export default app;
We are using some middlewares here:
cors: To handle Cross-Origin Resource Sharing.morgan: To log HTTP requests.express.json(): To parse JSON request body.express.urlencoded({ extended: true }): To parse URL-encoded request body.
Now we need to listen to the server on the port defined in .env file.We will listen to the server in index.ts file. Here is the index.ts file:
import * as dotenv from "dotenv";
dotenv.config();
import app from "./server";
app.listen(process.env.PORT, () => {
console.log(`Server is running on port ${process.env.PORT}`);
});
After this, you can run npm run dev to start the server in development mode. And after that you can visit http://localhost:YOUR_PORT/api to see the response Hello World.
Conclusion
In this article, we learned how to setup NodeJS and Typescript for REST API. In the future articles, we will learn how to use Prisma ORM to interact with the database and how to write validators for the request data.
You can find the complete code for this article here.