DEV Community

Setting Up a TypeScript + Express + MongoDB(Mongoose) Backend from Scratch

To set up a scalable and type-safe Node.js backend, we'll integrate Express, Mongoose, TypeScript, dotenv, and CORS. First, we initialize the project with npm init -y, which creates a package.json file with default settings. Next, we install the core dependencies, including Express, Mongoose, dotenv, and CORS, using npm install. We also install dev dependencies, including TypeScript and type definitions for Node.js, Express, and CORS. Then, we initialize TypeScript with tsc --init and update the tsconfig.json file to transpile source files from src/ to dist/. We add scripts to package.json to compile TypeScript, run the built JavaScript, and hot-reload using ts-node-dev. We create a .env file to store environment variables, such as the port and database URL, and add it to .gitignore. We create a basic project structure with src/, dist/, and other necessary files. In the server.ts file, we import dependencies, configure middleware, connect to MongoDB, and define routes. Finally, we build and run the project with npm run build and npm start, and our server should be live and connected to our MongoDB Atlas cluster.
favicon
dev.to
dev.to
Create attached notes ...