1️⃣ Step 1: Initialize Your Project
Start by setting up your project. Run the following commands:
mkdir scalable-api
cd scalable-api
npm init -y
npm install typescript ts-node express @types/express --save-dev
npx tsc --init
This sets up a basic TypeScript project with Express for your API.
2️⃣ Step 2: Create Your First API Endpoint
Create a new file src/index.ts and add the following code:
import express, { Request, Response } from 'express';
const app = express();
const PORT = 3000;
app.get('/', (req: Request, res: Response) => {
res.send('Hello, world!');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Run your server with:
npx ts-node src/index.ts
3️⃣ Step 3: Add Middleware
Middleware helps handle JSON requests and add additional functionality. Update your code:
app.use(express.json());
Now your API can handle JSON payloads. Try sending a POST request with some JSON data to test it.
4️⃣ Step 4: Modularize Your Code
Organize your project by separating routes and logic. Create a routes/hello.ts file:
import { Router } from 'express';
const router = Router();
router.get('/', (req, res) => {
res.send('Hello from the /hello endpoint!');
});
export default router;
In src/index.ts, use this router:
import helloRouter from './routes/hello';
app.use('/hello', helloRouter);
5️⃣ Step 5: Error Handling
Add centralized error handling to improve the robustness of your API:
app.use((err: Error, req: Request, res: Response, next: Function) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
6️⃣ Step 6: Environment Variables
Use environment variables to manage sensitive information like API keys or database credentials. Install dotenv:
npm install dotenv
Add a .env file:
PORT=3000
Update src/index.ts:
import dotenv from 'dotenv';
dotenv.config();
const PORT = process.env.PORT || 3000;
By following these steps, you now have a scalable and well-organized API with TypeScript and Express. 🚀
Ready to take it further? Add a database or authentication next!
Top comments (0)