Learn / Frameworks / Express / Introduction and Hello Server

Beginner 11 min

Introduction and Hello Server

Set up Node and Express and serve your first routes.

What you will learn

  • Initialize a Node project
  • Create an Express app
  • Define routes

Express is the most popular web framework for Node.js. It is deliberately minimal: a thin layer on top of Node's HTTP server that adds routing and a middleware system. Many bigger frameworks are built on it, and it is an excellent way to learn how web servers work.

Setup

Install Node.js (version 18 or newer), then create a project.

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

In package.json add "type": "module" to use modern import syntax.

// index.js
import express from "express";

const app = express();
const PORT = process.env.PORT || 3000;

app.get("/", (req, res) => {
  res.send("Hello, Express");
});

app.get("/health", (req, res) => {
  res.json({ status: "ok", time: new Date().toISOString() });
});

app.listen(PORT, () => console.log(`Listening on http://localhost:${PORT}`));
node index.js          # or: node --watch index.js to auto-restart

Open http://localhost:3000/. Each route takes a path and a handler receiving req (the request) and res (the response). Always finish a request by sending a response, otherwise the client hangs.

Common response methods

  • res.send(text): send text or HTML.
  • res.json(obj): send JSON with the right content type.
  • res.status(404).json({ ... }): set the status code first.
  • res.redirect("/new") and res.sendFile(path).

HTTP methods

app.get, app.post, app.put, app.patch and app.delete correspond to reading, creating, replacing, updating and removing resources.

Test with curl

curl -i http://localhost:3000/health shows the status line and headers as well as the body.

Try it yourself

Add GET /hello/:name that responds with Hello, <name>!. Look at the req.params object.

Show solution
app.get("/hello/:name", (req, res) => {
  res.send(`Hello, ${req.params.name}!`);
});