Skip to main content
Node.js & Express·Lesson 2 of 5

Express Setup and Basics

Express is the most popular Node.js web framework. It provides a thin layer of features on top of Node's built-in http module, making it fast and straightforward to build web applications and APIs.

Installing Express

Start a new project and install Express:

mkdir my-api && cd my-api
npm init -y
npm install express
npm install -D nodemon

Add a dev script to package.json:

{
  "scripts": {
    "start": "node src/app.js",
    "dev": "nodemon src/app.js"
  }
}

Your First Express Server

Ctrl+Enter
HTML
CSS
JS
Preview

Run it with npm run dev and visit http://localhost:3000 in your browser.

Understanding Request and Response

Every route handler receives req (request) and res (response) objects.

The Request Object

Ctrl+Enter
HTML
CSS
JS
Preview

The Response Object

Ctrl+Enter
HTML
CSS
JS
Preview
MethodUse For
res.json()Send JSON data
res.send()Send string, buffer, or object
res.status()Set HTTP status code
res.redirect()Redirect to another URL
res.set()Set response headers

Parsing Request Bodies

Express does not parse request bodies by default. Add the built-in middleware:

Ctrl+Enter
HTML
CSS
JS
Preview

Project Structure

Organize your code as the project grows:

my-api/
├── src/
   ├── app.js            # Express app setup
   ├── server.js          # Server startup
   ├── routes/
      ├── users.js       # User routes
      └── posts.js       # Post routes
   ├── controllers/
      ├── userController.js
      └── postController.js
   ├── middleware/
      ├── auth.js
      └── errorHandler.js
   └── config/
       └── index.js       # Configuration
├── package.json
└── .env

Separating App and Server

Ctrl+Enter
HTML
CSS
JS
Preview
Ctrl+Enter
HTML
CSS
JS
Preview

This separation makes your app easier to test because you can import app without starting the server.

Route Organization

Extract routes into separate files:

Ctrl+Enter
HTML
CSS
JS
Preview

Configuration Module

Centralize your configuration:

Ctrl+Enter
HTML
CSS
JS
Preview

Error Handling

Add a global error handler:

Ctrl+Enter
HTML
CSS
JS
Preview

Register it after all routes:

Ctrl+Enter
HTML
CSS
JS
Preview

Practical Exercise

Set up a complete Express project with proper structure:

Ctrl+Enter
HTML
CSS
JS
Preview

Key Takeaways

  • Express adds routing, middleware, and convenience methods on top of Node's http module.
  • Use express.json() middleware to parse JSON request bodies.
  • Separate your app setup from server startup for testability.
  • Organize routes into separate files using express.Router().
  • Always add a global error handler as the last middleware.