A comprehensive guide to building a robust backend using Express, TypeScript, and your choice of database (MongoDB or PostgreSQL).
Start by creating a new directory and initializing your project with TypeScript and Express.
If you prefer using Bun for a faster runtime and built-in package manager, check out our Monorepo guide which covers Bun initialization.
# Create project folder
mkdir hell-prisma
cd hello-prisma
# Initialize Node.js
npm init -y
# Install Support Packages
npm install typescript tsx @types/node --save-dev
# Install Express & Utilities
npm install express dotenv
npm install -D @types/express
# Initialize TypeScript
npx tsc --initWe are using ESM (EcmaScript Modules) effectively. Update your package.json to include:
Update your tsconfig.json for ESM compatibility:
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler",
"target": "ES2023",
"strict": true,
"esModuleInterop": true,
"ignoreDeprecations": "6.0"
}
}Create a basic server structure in src/index.ts.
import express, { Request, Response } from 'express';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.get('/', (req: Request, res: Response) => {
res.send('Server is running!');
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});Connect everything in your src/index.ts.
import express from 'express';
import dotenv from 'dotenv';
import userRoutes from './routes/user';
import connectDB from './db/connect';
dotenv.config();
const app = express();
app.use(express.json());
// Routes
app.use('/users', userRoutes);
const start = async () => {
try {
await connectDB();
app.listen(3000, () => console.log('Server started on port 3000'));
} catch (error) {
console.error(error);
process.exit(1);
}
};
start();Run your development server with tsx:
npx tsx src/index.ts