The App Object

`app` Is Where Routes, Middleware, and Settings Live

The App Object

`express()` returns an app object. Everything you'll do with Express starts with calling methods on it.

3 min read Level 1/5 #express#app#basics
What you'll learn
  • Understand the app object
  • Read app.METHOD, app.use, app.listen
  • Use app.set for configuration

const app = express() returns the app object — your handle on the framework. Everything else (routes, middleware, settings, listening) is a method on app.

The Five Methods You’ll Use Most

import express from "express";

const app = express();

app.use(middleware);              // mount middleware globally
app.get("/users", handler);        // route — handles GET /users
app.post("/users", handler);       // route — handles POST /users
app.set("view engine", "ejs");     // configure
app.listen(3000, callback);        // start the HTTP server

app.METHOD for Every HTTP Verb

app.get("/users",     listUsers);
app.post("/users",    createUser);
app.put("/users/:id", replaceUser);
app.patch("/users/:id", updateUser);
app.delete("/users/:id", deleteUser);
app.all("/admin/*", requireAdmin);   // any method

app.all matches every method — useful for blanket middleware on a path.

app.use for Middleware

app.use(express.json());              // built-in middleware
app.use(logger);                       // custom middleware
app.use("/api", apiRouter);            // mounted at a path

app.set and app.get (Settings)

app.set(name, value) stores a setting. app.get(name) reads it. (Yes — same get name as the route method. Express disambiguates by argument count.)

app.set("view engine", "ejs");
app.set("trust proxy", true);
app.set("json spaces", 2);

console.log(app.get("env"));   // "development" or "production"

Common settings:

SettingPurpose
envprocess.env.NODE_ENV (read-only)
trust proxyTrust X-Forwarded-* headers (behind a reverse proxy)
view engineDefault template engine
viewsTemplate directory
json spacesPretty-print JSON responses
case sensitive routing/Users/users
strict routing/users//users

app.listen Starts the Server

const server = app.listen(3000, () => {
  console.log("up on :3000");
});

Returns a Node HTTP server. Useful if you need to add WebSocket handling on the same port, or want graceful shutdown.

Multiple Apps

You can have several app instances in one process — useful when running a public API on one port and an admin API on another.

Routing Basics →