Skip to main content
The app object represents the Express application. Create it by calling the top-level express() function.
const express = require('express');
const app = express();
The app object has methods for routing HTTP requests, configuring middleware, rendering HTML views, registering template engines, and modifying application settings.

Properties

app.locals

An object containing local variables scoped to the application. These variables are available in all rendered templates.
app.locals
object
Local variables available to all views rendered by the application
app.locals.title = 'My App';
app.locals.email = 'support@example.com';

// Available in templates
// <%= title %> - outputs "My App"

app.mountpath

Contains the path pattern(s) on which a sub-app was mounted.
app.mountpath
string | array
The path or array of paths on which the app was mounted
const express = require('express');
const app = express();
const admin = express();

admin.get('/', (req, res) => {
  console.log(admin.mountpath); // '/admin'
  res.send('Admin Homepage');
});

app.use('/admin', admin);

Events

mount

The sub-app will emit a ‘mount’ event when mounted on a parent app.
const admin = express();

admin.on('mount', (parent) => {
  console.log('Admin Mounted');
  console.log(parent); // refers to the parent app
});

app.use('/admin', admin);

Methods

app.all(path, callback [, callback …])

Routes HTTP requests to the specified path with all HTTP methods (GET, POST, PUT, DELETE, etc.).
app.all('/secret', (req, res, next) => {
  console.log('Accessing the secret section...');
  next(); // pass control to the next handler
});

app.all('/api/*', requireAuthentication);

app.delete(path, callback [, callback …])

Routes HTTP DELETE requests to the specified path.
app.delete('/user/:id', (req, res) => {
  res.send(`Delete user ${req.params.id}`);
});

app.disable(name)

Sets the boolean setting name to false.
app.disable('x-powered-by');
app.disabled('x-powered-by'); // true

app.disabled(name)

Returns true if the boolean setting name is disabled (false).
app.disabled('trust proxy'); // false
app.disable('trust proxy');
app.disabled('trust proxy'); // true

app.enable(name)

Sets the boolean setting name to true.
app.enable('trust proxy');
app.enabled('trust proxy'); // true

app.enabled(name)

Returns true if the setting name is enabled (true).
app.enabled('trust proxy'); // false
app.enable('trust proxy');
app.enabled('trust proxy'); // true

app.engine(ext, callback)

Registers a template engine callback as ext. By default, Express will require() the engine based on the file extension.
app.engine('pug', require('pug').__express);
app.engine('html', require('ejs').renderFile);

app.get(name)

Returns the value of the app setting name.
app.get('title'); // undefined
app.set('title', 'My Site');
app.get('title'); // "My Site"

app.get(path, callback [, callback …])

Routes HTTP GET requests to the specified path.
app.get('/', (req, res) => {
  res.send('GET request to homepage');
});

app.get('/user/:id', (req, res) => {
  res.send(`User ${req.params.id}`);
});

app.listen([port[, host[, backlog]]][, callback])

Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen().
const server = app.listen(3000, () => {
  console.log('Server running on port 3000');
});

// Listening on specific host
app.listen(3000, 'localhost', () => {
  console.log('Server running on localhost:3000');
});

app.METHOD(path, callback [, callback …])

Routes HTTP requests where METHOD is the HTTP method (GET, POST, PUT, PATCH, DELETE, etc.) in lowercase.
// HTTP POST method
app.post('/', (req, res) => {
  res.send('POST request to homepage');
});

// HTTP PUT method
app.put('/user', (req, res) => {
  res.send('PUT request to /user');
});

// HTTP PATCH method
app.patch('/user/:id', (req, res) => {
  res.send(`PATCH request to user ${req.params.id}`);
});
Supported methods include: checkout, copy, delete, get, head, lock, merge, mkactivity, mkcol, move, m-search, notify, options, patch, post, purge, put, report, search, subscribe, trace, unlock, unsubscribe.

app.param([name], callback)

Adds callback triggers to route parameters. The name can be a single parameter name or an array of names.
app.param('user', (req, res, next, id) => {
  // Find user by ID
  User.find(id, (err, user) => {
    if (err) {
      next(err);
    } else if (user) {
      req.user = user;
      next();
    } else {
      next(new Error('User not found'));
    }
  });
});

// Multiple parameters
app.param(['id', 'page'], (req, res, next, value) => {
  console.log('Parameter:', value);
  next();
});

app.path()

Returns the canonical path of the app as a string.
const app = express();
const blog = express();
const blogAdmin = express();

app.use('/blog', blog);
blog.use('/admin', blogAdmin);

console.log(app.path()); // ''
console.log(blog.path()); // '/blog'
console.log(blogAdmin.path()); // '/blog/admin'

app.post(path, callback [, callback …])

Routes HTTP POST requests to the specified path.
app.post('/', (req, res) => {
  res.send('POST request to homepage');
});

app.post('/user', (req, res) => {
  res.send('Create new user');
});

app.put(path, callback [, callback …])

Routes HTTP PUT requests to the specified path.
app.put('/user/:id', (req, res) => {
  res.send(`Update user ${req.params.id}`);
});

app.render(view, [locals], callback)

Returns the rendered HTML of a view via the callback function. Accepts an optional parameter that is an object containing local variables for the view.
app.render('email', { name: 'Tobi' }, (err, html) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(html);
  // Send email with rendered HTML
});

app.route(path)

Returns an instance of a single route which you can then use to handle HTTP verbs with optional middleware. Use app.route() to avoid duplicate route naming and typos.
app.route('/events')
  .get((req, res) => {
    res.send('Get all events');
  })
  .post((req, res) => {
    res.send('Create an event');
  })
  .put((req, res) => {
    res.send('Update events');
  });

app.set(name, value)

Assigns setting name to value. You may store any value, but certain names can be used to configure the server’s behavior.
app.set('title', 'My Site');
app.set('email', 'support@example.com');

// Configuration settings
app.set('view engine', 'pug');
app.set('views', './views');

Application Settings

  • env - Environment mode (default: process.env.NODE_ENV or “development”)
  • view cache - Enables view template compilation caching (enabled in production by default)

app.use([path,] callback [, callback…])

Mounts middleware function(s) at the specified path. If path is not specified, it defaults to ”/”.
// Application-level middleware
app.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

// Middleware for specific path
app.use('/user/:id', (req, res, next) => {
  console.log('Request Type:', req.method);
  next();
});

// Mount a router
const router = express.Router();
app.use('/api', router);

// Mount an Express app
const admin = express();
app.use('/admin', admin);

// Error-handling middleware (must have 4 arguments)
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

Complete Example

const express = require('express');
const app = express();

// Settings
app.set('view engine', 'pug');
app.set('views', './views');
app.set('trust proxy', true);

// Locals
app.locals.title = 'My Application';
app.locals.strftime = require('strftime');

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));

// Parameter middleware
app.param('user', (req, res, next, id) => {
  User.find(id, (err, user) => {
    if (err) return next(err);
    req.user = user;
    next();
  });
});

// Routes
app.get('/', (req, res) => {
  res.render('index');
});

app.route('/users')
  .get((req, res) => res.json(users))
  .post((req, res) => res.json({ created: true }));

// Start server
app.listen(3000, () => {
  console.log('Server running on port 3000');
});