The app Object
The application object returned by express() is where you register routes, middleware and settings.
Syntax
const app = express();Calling express() returns the application object. It is the central hub of your program. You use it to:
- Register routes with
app.get(),app.post(), and so on. - Add middleware with
app.use(). - Store settings with
app.set('name', value)and read them withapp.get('name'). - Start listening with
app.listen().
Most apps create exactly one app object and export or run it.
Example
const express = require('express');
const app = express();
// Store a setting
app.set('appName', 'SoundsCode API');
app.get('/', (req, res) => {
res.send('Welcome to ' + app.get('appName'));
});
app.listen(3000);When to use it
- A developer stores the app object in a module so both the HTTP server and test helpers can import it without re-initialising Express.
- A senior engineer uses app.set() on the app object to configure template engine settings once during bootstrap.
- A team accesses app.locals on the app object to share application-wide constants such as the app name with all templates.
More examples
Creating and exporting the app
Creates the app object and exports it so server.js and test files can both import the same instance.
const express = require('express');
const app = express();
// Register routes and middleware on app
app.get('/health', (req, res) => res.json({ ok: true }));
module.exports = app;Using app.set for settings
Demonstrates storing and retrieving arbitrary settings on the app object with app.set / app.get.
const express = require('express');
const app = express();
app.set('appName', 'MyAPI');
app.set('version', '2.0');
app.get('/info', (req, res) => {
res.json({
name: app.get('appName'),
version: app.get('version'),
});
});Sharing data via app.locals
Shows app.locals as a simple key-value store accessible across all routes and middleware.
const express = require('express');
const app = express();
app.locals.siteName = 'SoundsCode';
app.locals.startedAt = new Date();
app.get('/meta', (req, res) => {
res.json(app.locals);
});
app.listen(3000);
Discussion