02 Project Setup Express Koa
title: Project Setup with Express and Koa for Node.js REST APIs weight: 12 date: 2026-06-28 lastmod: 2026-06-28 description: Set up Express or Koa for Node.js REST APIs including project initialization, dependency installation, and basic server configuration for HTTP routing. tags: [api-development, nodejs]
Setting up Express or Koa for Node.js REST APIs involves initializing a Node.js project, installing the framework, and configuring the server with middleware for JSON parsing, routing, and error handling.
```mermaid
flowchart TD
A[Project Setup] --> B[npm init]
B --> C[Install express]
C --> D[Create app.js]
D --> E[Middleware]
D --> F[Routes]
D --> G[Error Handler]
E --> H[app.use(express.json())]
F --> I[app.get('/api/users', handler)]
style A fill:#e1f5fe
style B fill:#f3e5f5
style D fill:#c8e6c9
Start by running npm init to create package.json. Install express or koa. Create the main server file that configures middleware, routes, and starts listening on a port. Use a development tool like nodemon for automatic restarts.
Think of project setup like preparing a kitchen before cooking. You install the appliances (npm install express), set up the countertops (middleware), organize the ingredients (routes), and turn on the stove (app.listen).
Example: Express Project Setup
// Initialize project
// mkdir my-api && cd my-api
// npm init -y
// npm install express cors helmet morgan
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(helmet());
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
// Health check
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Expected output:
Server running on port 3000
Example: Koa Project Setup
// npm install koa koa-router koa-body @koa/cors
const Koa = require('koa');
const Router = require('koa-router');
const { koaBody } = require('koa-body');
const cors = require('@koa/cors');
const app = new Koa();
const router = new Router({ prefix: '/api' });
const PORT = process.env.PORT || 3000;
app.use(cors());
app.use(koaBody());
router.get('/health', (ctx) => {
ctx.body = { status: 'ok', timestamp: new Date().toISOString() };
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(PORT, () => {
console.log(`Koa server running on port ${PORT}`);
});
Expected output:
Koa server running on port 3000
Example: Nodemon for Development
{
"name": "my-api",
"scripts": {
"start": "node src/app.js",
"dev": "nodemon src/app.js"
},
"dependencies": {
"express": "^4.18.0"
},
"devDependencies": {
"nodemon": "^3.0.0"
}
}
Expected output:
$ npm run dev
[nodemon] watching path: src/**/*
[nodemon] starting `node src/app.js`
Server running on port 3000
Common Mistakes
- Missing express.json() middleware — Without express.json(), req.body is undefined for JSON requests. This middleware parses incoming JSON payloads.
- Running on port 80 without a reverse proxy — Port 80 requires root privileges. Use a reverse proxy like Nginx to forward requests from port 80 to your Node.js app.
- Not using environment variables for configuration — Hard-coding the port number or database URL makes the app less portable. Use environment variables with sensible defaults.
- Forgetting to handle CORS — Browser-based clients need the CORS middleware to access the API. Without it, cross-origin requests fail with CORS errors.
- Installing unnecessary dependencies — Every dependency increases the attack surface and maintenance burden. Install only what you need.
Practice Questions
- What does express.json() middleware do?
- Why should you use helmet in production?
- What is the purpose of the morgan middleware?
- How does Koa differ from Express in its approach to middleware?
- Challenge: Set up an Express project with custom middleware that logs the request method, URL, and response time. Add a catch-all error handler. Test with various endpoints.
FAQ
Mini Project
Set up an Express project with the following middleware: helmet for security, cors for cross-origin support, morgan for logging, express.json() for body parsing, and a custom error handler. Create a health check endpoint and a test route. Use nodemon for development.
What's Next
Now learn about folder structure in the next lesson on Building REST APIs with Node.js.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro