Skip to content

02 Project Setup Express Koa

DodaTech 4 min read

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

  1. Missing express.json() middleware — Without express.json(), req.body is undefined for JSON requests. This middleware parses incoming JSON payloads.
  2. 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.
  3. 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.
  4. Forgetting to handle CORS — Browser-based clients need the CORS middleware to access the API. Without it, cross-origin requests fail with CORS errors.
  5. Installing unnecessary dependencies — Every dependency increases the attack surface and maintenance burden. Install only what you need.

Practice Questions

  1. What does express.json() middleware do?
  2. Why should you use helmet in production?
  3. What is the purpose of the morgan middleware?
  4. How does Koa differ from Express in its approach to middleware?
  5. 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

Should I use Express or Koa for a new project?

Express has a larger ecosystem and more tutorials. Koa has a cleaner async/await design. Choose Express for wider community support, Koa for a more modern API.

What is the difference between app.use and app.get?

app.use applies middleware to all HTTP methods. app.get handles only GET requests. Use app.use for middleware that runs for every request.

Why do I need CORS middleware?

Browsers block cross-origin HTTP requests for security. CORS middleware adds headers that tell the browser which origins are allowed to access the API.

Should I use nodemon in production?

No, nodemon is a development tool. In production, use a process manager like PM2 or run directly with node.

What is the best way to structure an Express project?

Separate routes, controllers, models, middleware, and config into different folders. Use a layered architecture for maintainability.

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