
Learn how to create a type-safe REST API with Express and TypeScript, configured for seamless Vercel deployment. This comprehensive guide covers project setup, TypeScript configuration, API development, and deployment best practices.
In this guide, we’ll walk through building a simple REST API using Express with TypeScript, designed for easy deployment to Vercel. The API will manage a collection of blog posts stored in memory and include endpoints to create and retrieve posts. We’ll ensure type safety, configure environment variables, and follow modern backend development practices to create a scalable and maintainable project.
This tutorial is perfect for developers looking to:
The API includes the following features:
Start by creating a new Node.js project:
npm init -y && npm pkg set name="arfat.app" description="TypeScript Express API" author="Arfatur Rahman"
This creates a package.json file with default values, setting the project name, description, and author.
Install the necessary runtime dependencies:
npm i express cors axios body-parser dotenv
Add development dependencies for TypeScript and tooling:
npm i -D typescript ts-node-dev nodemon @types/express @types/node @types/cors
Generate a tsconfig.json file to configure TypeScript:
npx tsc --init --rootDir src --outDir dist
This sets the source files in the src directory and compiled output in the dist directory.
Here’s the recommended project structure:
project-root/ ├── src/ │ └── index.ts # Main application file ├── .env # Environment variables ├── .gitignore # Files to ignore in Git ├── package.json # Project configuration ├── tsconfig.json # TypeScript configuration └── vercel.json # Vercel deployment configuration
The tsconfig.json file configures the TypeScript compiler:
{ "compilerOptions": { "target": "es2016", "module": "commonjs", "rootDir": "src", "outDir": "dist", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true }, "include": ["src"], "exclude": ["node_modules"] }
Key settings:
Update the scripts section in package.json to include:
{ "scripts": { "dev": "ts-node-dev --respawn --transpile-only --exit-child src/index.ts" } }
The dev script runs the server in development mode with hot reloading and faster compilation.
The main application file sets up the Express server and defines the API:
import express, { Request, Response, Application } from "express"; import { randomBytes } from "crypto"; import bodyParser from "body-parser"; import dotenv from "dotenv"; import cors from "cors"; // Configuration dotenv.config(); const PORT = process.env.PORT || 4000; // Types interface Post { id: string; title: string; } interface Posts { [key: string]: Post; } // App State const posts: Posts = {}; // Express App Setup const app: Application = express(); app.use(bodyParser.json()); app.use(cors()); // Helper Functions const generateId = (): string => randomBytes(4).toString("hex"); // Controllers const getRoot = (req: Request, res: Response) => { res.send("Assalamualikum"); }; const getAllPosts = (req: Request, res: Response) => { res.json(posts); }; const createPost = (req: Request, res: Response) => { const id = generateId(); const { title } = req.body; if (!title) { res.status(400).json({ error: "Title is required" }); return; } posts[id] = { id, title }; res.status(201).json(posts[id]); }; // Routes app.get("/", getRoot); app.get("/posts", getAllPosts); app.post("/posts", createPost); // Server Initialization const startServer = async (): Promise<void> => { try { app.listen(PORT, () => { console.log(`Server is running on port: ${PORT}`); }); } catch (error) { console.error(`Failed to start server: ${error}`); process.exit(1); } }; startServer();
This file includes:
The vercel.json file configures Vercel deployment:
{ "version": 2, "builds": [ { "src": "src/index.ts", "use": "@vercel/node" } ], "routes": [ { "src": "/(.*)", "dest": "src/index.ts" } ] }
This configuration:
Create a .env file for environment variables:
PORT=4000
Create a .gitignore file to exclude sensitive files:
.env node_modules
You can automate this with:
echo -e 'PORT=4000' > .env && echo -e '.env\nnode_modules' > .gitignore
Create Configuration Files:
Start the Development Server:
npm run dev
The server will:
Install the Vercel CLI globally:
npm i -g vercel
Check the Vercel CLI version:
npx vercel --version
Authenticate with Vercel:
npx vercel login
For a preview deployment:
npx vercel
For a production deployment:
npx vercel --prod
TypeScript interfaces ensure type safety:
interface Post { id: string; title: string; } interface Posts { [key: string]: Post; }
Benefits include:
Using TypeScript with Express provides:
This guide demonstrated how to build a type-safe REST API using Express and TypeScript, configured for deployment to Vercel. By following modern backend development practices, including proper project structure, TypeScript configuration, and environment variable management, you can create a robust and scalable API. Deploying to Vercel ensures your API is accessible globally with minimal setup.
Try building this API and deploying it yourself! For more advanced features, consider adding:
Hi, I’m Arfatur Rahman, a Full-Stack Developer from Chittagong, Bangladesh, specializing in AI-powered applications, RAG-based chatbots, and scalable web platforms. I’ve worked with tools like Next.js, LangChain, OpenAI, Azure, and Supabase, building everything from real-time dashboards to SaaS products with payment integration. Passionate about web development, vector databases, and AI integration, I enjoy sharing what I learn through writing and open-source work.
Connect with me:
Comments
No Comments
Leave a replay
Your email address will not be publish. Required fields are marked *