This guide provides a step-by-step process for setting up a basic web server using Express.js and TypeScript. Prerequisites Ensure you have the following installed:
Node.js ( Latest LTS recommended ) npm (or yarn/pnpm)
Start by creating a new directory for your project and initializing a new Node.js project.
mkdir servercd servernpm init -yInstall Express and the necessary TypeScript-related packages. Production Dependencies
Install Express, the web framework
npm install express cors dotenvInstall TypeScript, the type definitions for Express and Node.js, and tsx for running the server without a pre-compiled step.
npm install -D typescript tsx @types/node ts-node @types/express nodemon @types/corsCreate a tsconfig.json file in your project root to configure the TypeScript compiler. You can generate a default file using the following command
npx tsc --initFor a basic setup, ensure your tsconfig.json has at least these settings:
{
"compilerOptions": {
"target": "ES2020",
"module": "nodenext",
"moduleResolution":"nodenext",
"outDir": "./dist",
"rootDir": "./",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"./**/*.ts"
],
"exclude": [
"node_modules"
]
}Create a main server file, for example server.ts.
Add the following basic Express server code to server.ts:
import "dotenv/config";
import express, { Request, Response } from 'express';
import cors from "cors";
const app = express();
// Middleware
app.use(cors())
app.use(express.json());
const port = process.env.PORT || 3000;
app.get('/', (req: Request, res: Response) => {
res.send('Server is Live!');
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});Modify your package.json file to add scripts for starting the server using tsx
"scripts": {
"start": "tsx server.ts",
"server": "nodemon --exec tsx server.ts",
"build": "tsc"
}"type": "module"Start your server using the new script:
npm run serverYou should see the message: Server is running at http://localhost:3000
Open your web browser and navigate to http://localhost:3000 to see the
"Server is Live!" message.