Creating an Express App
The main Express app file is typically named index.js, app.js, or server.js. A typical file contains imports, app initialisation, middleware, routes, and a call to app.listen().
Hello World
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Run it with:
node index.js
Open http://localhost:3000 in your browser and you will see Hello World.
Using ES modules
If your package.json has "type": "module", use import syntax instead:
import express from 'express';
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
The rest of the Express API is identical regardless of which module system you use.
How it works
const express = require('express') loads the Express module.
const app = express() creates an Express application instance. This object handles all requests and responses.
app.get('/', ...) defines a route. When a GET request comes in for /, Express calls the callback function with the request (req) and response (res) objects.
res.send('Hello World') sends the response. Express sets the Content-Type header automatically.
app.listen(PORT, callback) starts the server. process.env.PORT lets the app use a port set by the hosting environment. It falls back to 3000 for local development.
Project structure
A typical Express project looks like this:
my-project/
├── index.js # entry point
├── package.json
├── node_modules/
├── routes/ # route files (one per resource)
├── controllers/ # business logic called by routes
├── middleware/ # custom middleware
└── public/ # static files (HTML, CSS, images)
routes/: one file per resource (e.g.routes/users.js,routes/posts.js)controllers/: functions that contain the logic for each routemiddleware/: reusable middleware such as authentication checkspublic/: static assets served directly to the browser
What to read next
- Routing : define routes for different URLs and HTTP methods
- Middleware : add functions that run on every request