How to initialize an Express application — Basic
Create the Express app instance and register core middleware before defining routes.
Learn: Every Express API starts with a single app instance. Register global middleware (JSON parsing, logging, CORS) before routes so every request is prepared the same way. Keep app.js focused on wiring; move route logic into routers as the project grows.
Supplementary examples
Minimal app with a health check
const express = require("express");
const app = express();
app.get("/health", (req, res) => res.json({ ok: true }));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Listening on ${PORT}`));Register JSON parsing before routes
const express = require("express");
const app = express();
app.use(express.json()); // must run before handlers that read req.bodyCourse example
{
"name": "deploying-the-server",
"version": "1.0.0",
"engines": {
"node": "12.13.0"
},
"description": "",
"main": "server.js",
"scripts": {
"start": "node server",
"server": "nodemon server.js",
"client": "npm start --prefix client"
},
"keywords": [],
"dependencies": {
"express": "^4.17.1",
"cors": "^2.8.5"
},
"devDependencies": {
"nodemon": "^2.0.3"
}
}
Additional references & examples
- Node.js documentation
Official Node APIs: modules, events, and runtime behavior.
- Express.js guide
Routing, middleware order, and request/response lifecycle.
- MDN: Introduction to Express
Conceptual overview of Express in a full-stack context.