Installing Express

Assuming you’ve already installed Node.js, create a directory to hold your application, and make that your working directory.

$ mkdir myapp
$ cd myapp

Use the npm init command to create a package.json file for your application. For more information on how package.json works, see Specifics of npm’s package.json handling.

$ npm init

This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:

entry point: (index.js)

Enter app.js, or whatever you want the name of the main file to be. If you want it to be index.js, hit RETURN to accept the suggested default file name.

Now install Express in the myapp directory and save it in the dependencies list. For example:

$ npm install express

Hello world example

The code below is essentially the simplest Express app you can create. It is a single file app — not what you’d get if you use the Express generator, which creates the scaffolding for a full app with numerous JavaScript files, templates, and sub-directories.

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

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

This app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (/) route. For every other path, it will respond with a 404 Not Found.

To run this app locally, first follow the installation guide above. Then in the myapp directory, create a file named app.js and copy in the code from the example above.

The req (request) and res (response) objects are the exact same objects that Node provides, so you can invoke req.pipe(), req.on('data', callback), and anything else you would do with those objects without Express.

Run the app with the following command:

$node app.js

Then, load http://localhost:3000/ in a browser to see the output.

Basic routing

Routing refers to determining how an application responds to a client request to a particular endpoint. An endpoint is a URI (or path) and a specific HTTP request method (GET, POST, etc).

Each route can have one or more handler functions, which are executed when the route is matched.

This tutorial assumes that an instance of express named app is created and that the server is running. For instructions on how to do this, see the Hello world example above.

Route definition has the following structure:

app.method(path, handler);

Where:

Examples

The following examples illustrate how to define simple routes.

Respond to a POST request on the root route (/), or application's home page:

app.post('/', (req, res) => {
  res.send('Got a POST request');
});

Respond to a PUT request to the /user route:

app.put('/user', (req, res) => {
  res.send('Got a PUT request at /user');
});

Respond to a DELETE request to the /user route:

app.delete('/user', (req, res) => {
  res.send('Got a DELETE request at /user');
})

For more details about routing, see the routing guide on the Express website.

Serving static files

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

The function signature is:

express.static(root, [options]);

The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.static.

For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:

app.use(express.static('public'));

Now you can load files that are in the public directory, for example:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.

To use multiple static asset directories, call the express.static middleware function multiple times:

app.use(express.static('public'));
app.use(express.static('files'));

Express looks up the files in the order in which you set the static directories with the express.static middleware function.

To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:

app.use('/static', express.static('public'));

Now, you can load the files that are in the public directory from the /static path prefix.

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

Note, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve, like the below:

app.use('/static', express.static(path.join(__dirname, 'public')))

For more details about the serve-static function and its options, see serve-static.

FAQ

How should I structure my application?

There is no definitive answer to this question. The answer depends on the scale of your application and the team that is involved. To be as flexible as possible, Express makes no assumptions in terms of structure.

Routes and other application-specific logic can live in as many files as you wish, in any directory structure you prefer. View the following examples for inspiration:

Also, there are third-party extensions for Express, which simplify some of these patterns:

How do I define models?

Express has no notion of a database. This concept is left up to third-party Node modules, allowing you to interface with nearly any database.

How can I authenticate users?

Authentication is another opinionated area that Express does not venture into. You may use any authentication scheme you wish. For a simple username / password scheme, see this example.

Which template engines does Express support?

Express supports any template engine that conforms with the (path, locals, callback) signature. To normalize template engine interfaces and caching, see the consolidate.js project for support. Unlisted template engines might still support the Express signature.

For more information, see Using template engines with Express.

How do I handle 404 responses?

In Express, 404 responses are not the result of an error, so error-handler middleware will not capture them. This is because a 404 response indicates the absence of additional work to do. In other words, Express has executed all middleware functions and routes, and found that none of them responded.

To handle this situation, simply add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response:

app.use((req, res, next) => {
  res.status(404).send("Sorry can't find that!");
});

Add routes dynamically at runtime on an instance of express.Router() so the routes are not superseded by a middleware function.

How do I setup an error handler?

You define error-handling middleware in the same way as other middleware, except with four arguments instead of three; specifically with the signature (err, req, res, next):

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

For more information, see Error handling on the Express.js site.

How do I render plain HTML?

You don’t! There’s no need to “render” HTML with the res.render() function. If you have a specific file, use the res.sendFile() function. If you are serving many assets from a directory, use the express.static() middleware function.

Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 United States License.