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!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay