DEV Community

DAITEN - official -
DAITEN - official -

Posted on

Want to build a scalable API with TypeScript? Here's a step-by-step guide to get started! 🧵

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
Enter fullscreen mode Exit fullscreen mode

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}`);
});
Enter fullscreen mode Exit fullscreen mode

Run your server with:

npx ts-node src/index.ts
Enter fullscreen mode Exit fullscreen mode

3️⃣ Step 3: Add Middleware
Middleware helps handle JSON requests and add additional functionality. Update your code:

app.use(express.json());
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

In src/index.ts, use this router:

import helloRouter from './routes/hello';

app.use('/hello', helloRouter);
Enter fullscreen mode Exit fullscreen mode

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!');
});
Enter fullscreen mode Exit fullscreen mode

6️⃣ Step 6: Environment Variables
Use environment variables to manage sensitive information like API keys or database credentials. Install dotenv:

npm install dotenv
Enter fullscreen mode Exit fullscreen mode

Add a .env file:

PORT=3000
Enter fullscreen mode Exit fullscreen mode

Update src/index.ts:

import dotenv from 'dotenv';

dotenv.config();
const PORT = process.env.PORT || 3000;
Enter fullscreen mode Exit fullscreen mode

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)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more