# Express examples and more

# Express examples

> Explore a collection of Express.js application examples covering various use cases, integrations, and advanced configurations to help you learn and build your projects.

# Express examples

This page contains list of examples using Express.

- [auth](https://github.com/expressjs/express/tree/master/examples/auth) - Authentication with login and password
- [content-negotiation](https://github.com/expressjs/express/tree/master/examples/content-negotiation) - HTTP content negotiation
- [cookie-sessions](https://github.com/expressjs/express/tree/master/examples/cookie-sessions) - Working with cookie-based sessions
- [cookies](https://github.com/expressjs/express/tree/master/examples/cookies) - Working with cookies
- [downloads](https://github.com/expressjs/express/tree/master/examples/downloads) - Transferring files to client
- [ejs](https://github.com/expressjs/express/tree/master/examples/ejs) - Working with Embedded JavaScript templating (ejs)
- [error-pages](https://github.com/expressjs/express/tree/master/examples/error-pages) - Creating error pages
- [error](https://github.com/expressjs/express/tree/master/examples/error) - Working with error middleware
- [hello-world](https://github.com/expressjs/express/tree/master/examples/hello-world) - Simple request handler
- [markdown](https://github.com/expressjs/express/tree/master/examples/markdown) - Markdown as template engine
- [multi-router](https://github.com/expressjs/express/tree/master/examples/multi-router) - Working with multiple Express routers
- [mvc](https://github.com/expressjs/express/tree/master/examples/mvc) - MVC-style controllers
- [online](https://github.com/expressjs/express/tree/master/examples/online) - Tracking online user activity with `online` and `redis` packages
- [params](https://github.com/expressjs/express/tree/master/examples/params) - Working with route parameters
- [resource](https://github.com/expressjs/express/tree/master/examples/resource) - Multiple HTTP operations on the same resource
- [route-map](https://github.com/expressjs/express/tree/master/examples/route-map) - Organizing routes using a map
- [route-middleware](https://github.com/expressjs/express/tree/master/examples/route-middleware) - Working with route middleware
- [route-separation](https://github.com/expressjs/express/tree/master/examples/route-separation) - Organizing routes per each resource
- [search](https://github.com/expressjs/express/tree/master/examples/search) - Search API
- [session](https://github.com/expressjs/express/tree/master/examples/session) - User sessions
- [static-files](https://github.com/expressjs/express/tree/master/examples/static-files) - Serving static files
- [vhost](https://github.com/expressjs/express/tree/master/examples/vhost) - Working with virtual hosts
- [view-constructor](https://github.com/expressjs/express/tree/master/examples/view-constructor) - Rendering views dynamically
- [view-locals](https://github.com/expressjs/express/tree/master/examples/view-locals) - Saving data in request object between middleware calls
- [web-service](https://github.com/expressjs/express/tree/master/examples/web-service) - Simple API service

## Additional examples

These are some additional examples with more extensive integrations.

Warning

This information refers to third-party sites, products, or modules that are not maintained by the Expressjs team. Listing here does not constitute an endorsement or recommendation from the Expressjs project team.

- [prisma-fullstack](https://github.com/prisma/prisma-examples/tree/latest/pulse/fullstack-simple-chat) - Fullstack app with Express and Next.js using [Prisma](https://www.npmjs.com/package/prisma) as an ORM
- [prisma-rest-api-ts](https://github.com/prisma/prisma-examples/tree/latest/orm/express) - REST API with Express in TypeScript using [Prisma](https://www.npmjs.com/package/prisma) as an ORM

  [Edit this page](https://github.com/expressjs/expressjs.com/edit/gh-pages/en/starter/examples.md          )

---

# FAQ

> Find answers to frequently asked questions about Express.js, including topics on application structure, models, authentication, template engines, error handling, and more.

# 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:

- [Route listings](https://github.com/expressjs/express/blob/4.13.1/examples/route-separation/index.js#L32-L47)
- [Route map](https://github.com/expressjs/express/blob/4.13.1/examples/route-map/index.js#L52-L66)
- [MVC style controllers](https://github.com/expressjs/express/tree/master/examples/mvc)

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

- [Resourceful routing](https://github.com/expressjs/express-resource)

## 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.

See [LoopBack](http://loopback.io) for an Express-based framework that is centered around models.

## 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](https://github.com/expressjs/express/tree/master/examples/auth).

## 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](https://github.com/visionmedia/consolidate.js)
project for support. Unlisted template engines might still support the Express signature.

For more information, see [Using template engines with Express](https://expressjs.com/en/guide/using-template-engines.html).

## How do I handle 404 responses?

In Express, 404 responses are not the result of an error, so
the error-handler middleware will not capture them. This behavior is
because a 404 response simply 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. All you need to
do is 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](https://expressjs.com/en/guide/error-handling.html).

## 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.

## What version of Node.js does Express require?

- [Express 4.x](https://expressjs.com/en/4x/api.html) requires Node.js 0.10 or higher.
- [Express 5.x](https://expressjs.com/en/5x/api.html) requires Node.js 18 or higher.

  [Edit this page](https://github.com/expressjs/expressjs.com/edit/gh-pages/en/starter/faq.md          )

---

# Express application generator

> Learn how to use the Express application generator tool to quickly create a skeleton for your Express.js applications, streamlining setup and configuration.

# Express application generator

Use the application generator tool, `express-generator`, to quickly create an application skeleton.

You can run the application generator with the `npx` command (available in Node.js 8.2.0).

```
$ npx express-generator
```

For earlier Node versions, install the application generator as a global npm package and then launch it:

```
$ npm install -g express-generator
$ express
```

Display the command options with the `-h` option:

```
$ express -h

  Usage: express [options] [dir]

  Options:

    -h, --help          output usage information
        --version       output the version number
    -e, --ejs           add ejs engine support
        --hbs           add handlebars engine support
        --pug           add pug engine support
    -H, --hogan         add hogan.js engine support
        --no-view       generate without view engine
    -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
    -c, --css <engine>  add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
        --git           add .gitignore
    -f, --force         force on non-empty directory
```

For example, the following creates an Express app named *myapp*. The app will be created in a folder named *myapp* in the current working directory and the view engine will be set to [Pug](https://pugjs.org/):

```
$ express --view=pug myapp

   create : myapp
   create : myapp/package.json
   create : myapp/app.js
   create : myapp/public
   create : myapp/public/javascripts
   create : myapp/public/images
   create : myapp/routes
   create : myapp/routes/index.js
   create : myapp/routes/users.js
   create : myapp/public/stylesheets
   create : myapp/public/stylesheets/style.css
   create : myapp/views
   create : myapp/views/index.pug
   create : myapp/views/layout.pug
   create : myapp/views/error.pug
   create : myapp/bin
   create : myapp/bin/www
```

Then install dependencies:

```
$ cd myapp
$ npm install
```

On MacOS or Linux, run the app with this command:

```
$ DEBUG=myapp:* npm start
```

On Windows Command Prompt, use this command:

```
> set DEBUG=myapp:* & npm start
```

On Windows PowerShell, use this command:

```
PS> $env:DEBUG='myapp:*'; npm start
```

Then, load `http://localhost:3000/` in your browser to access the app.

The generated app has the following directory structure:

```
.
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.pug
    ├── index.pug
    └── layout.pug

7 directories, 9 files
```

The app structure created by the generator is just one of many ways to structure Express apps. Feel free to use this structure or modify it to best suit your needs.

   [Edit this page](https://github.com/expressjs/expressjs.com/edit/gh-pages/en/starter/generator.md          )

---

# Hello world example

> Get started with Express.js by building a simple 'Hello World' application, demonstrating the basic setup and server creation for beginners.

# Hello world example

Embedded 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](https://expressjs.com/en/starter/generator.html), which creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and sub-directories for various purposes.

```
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 on port ${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 (`/`) or *route*. For every other path, it will respond with a **404 Not Found**.

### Running Locally

First create a directory named `myapp`, change to it and run `npm init`. Then, install `express` as a dependency, as per the [installation guide](https://expressjs.com/en/starter/installing.html).

In the `myapp` directory, create a file named `app.js` and copy the code from the example above.

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

Run the app with the following command:

```
$ node app.js
```

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

  [Edit this page](https://github.com/expressjs/expressjs.com/edit/gh-pages/en/starter/hello-world.md          )

---

# Installing

> Learn how to install Express.js in your Node.js environment, including setting up your project directory and managing dependencies with npm.

# Installing

Assuming you’ve already installed [Node.js](https://nodejs.org/), create a directory to hold your application, and make that your working directory.

- [Express 4.x](https://expressjs.com/en/4x/api.html) requires Node.js 0.10 or higher.
- [Express 5.x](https://expressjs.com/en/5x/api.html) requires Node.js 18 or higher.

```
$ 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](https://docs.npmjs.com/files/package.json).

```
$ 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
```

To install Express temporarily and not add it to the dependencies list:

```
$ npm install express --no-save
```

By default with version npm 5.0+, `npm install` adds the module to the `dependencies` list in the `package.json` file; with earlier versions of npm, you must specify the `--save` option explicitly. Then, afterwards, running `npm install` in the app directory will automatically install modules in the dependencies list.

   [Edit this page](https://github.com/expressjs/expressjs.com/edit/gh-pages/en/starter/installing.md          )

---

# Serving static files in Express

> Understand how to serve static files like images, CSS, and JavaScript in Express.js applications using the built-in 'static' middleware.

# Serving static files in Express

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

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](https://expressjs.com/en/5x/api.html#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 the files that are in the `public` directory:

```
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 assets 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.

Note

For best results, [use a reverse proxy](https://expressjs.com/en/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets.

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](https://expressjs.com/en/5x/api.html#app.use) 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
```

However, 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:

```
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))
```

For more details about the `serve-static` function and its options, see  [serve-static](https://expressjs.com/resources/middleware/serve-static.html).

  [Edit this page](https://github.com/expressjs/expressjs.com/edit/gh-pages/en/starter/static-files.md          )

---

# Version Support

> Find information about the support schedule for different Express.js versions, including which versions are currently maintained and end-of-life policies.

# Version Support

Only the latest version of any given major release line is supported.

Versions that are EOL (end-of-life) *may* receive updates for critical security vulnerabilities, but the Express team offers no guarantee and does not plan to address or release fixes for any issues found.

| Major Version | Minimum Node.js Version | Support Start Date | Support End Date |
| --- | --- | --- | --- |
| v5.x | 18 | September 2024 | ongoing |
| v4.x | 0.10.0 | April 2014 | ongoing |
| v3.x | 0.8.0 | October 2012 | July 2015 |
| v2.x | 0.4.1 | March 2011 | July 2012 |
| v1.x | 0.2.0 | December 2010 | March 2011 |
| v0.14.x | 0.1.98 | December 2010 | December 2010 |

## Commercial Support Options

If you are unable to update to a supported version of Express, please contact one of our partners to receive security updates:

- [HeroDevs Never-Ending Support](http://www.herodevs.com/support/express-nes?utm_source=expressjs&utm_medium=link&utm_campaign=express_eol_page)

 [Edit this page](https://github.com/expressjs/expressjs.com/edit/gh-pages/en/support/index.md          )
