W↓
All docs
🔑
Sign Up/Sign In
expressjs.com/en/starter/ (+1)
Public Link
Jun 12, 2025, 1:54:19 PM - complete - 101.3 kB
Created by:
****ad@vlad.studio
Starting URLs:
https://expressjs.com/en/starter/installing.html
CSS Selector:
main
Crawl Prefixes:
https://expressjs.com/en/starter/
https://expressjs.com/en/guide/
## Page: https://expressjs.com/en/starter/installing.html # Installing Assuming you’ve already installed Node.js, create a directory to hold your application, and make that your working directory. * Express 4.x requires Node.js 0.10 or higher. * Express 5.x 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. $ 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. ### Next: Hello World Edit this page --- ## Page: https://expressjs.com/en/starter/hello-world.html # 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, 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. 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. ### Previous: Installing Next: Express Generator Edit this page --- ## Page: https://expressjs.com/en/starter/generator.html # 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: $ 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. ### Previous: Hello World Next: Basic routing Edit this page --- ## Page: https://expressjs.com/en/starter/basic-routing.html # Basic routing _Routing_ refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). Each route can have one or more handler functions, which are executed when the route is matched. Route definition takes the following structure: app.METHOD(PATH, HANDLER) Where: * `app` is an instance of `express`. * `METHOD` is an HTTP request method, in lowercase. * `PATH` is a path on the server. * `HANDLER` is the function executed when the route is matched. This tutorial assumes that an instance of `express` named `app` is created and the server is running. If you are not familiar with creating an app and starting it, see the Hello world example. The following examples illustrate defining simple routes. Respond with `Hello World!` on the homepage: app.get('/', (req, res) => { res.send('Hello World!') }) Respond to POST request on the root route (`/`), the 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. ### Previous: Express application generator Next: Serving static files in Express Edit this page --- ## Page: https://expressjs.com/en/starter/static-files.html # 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. 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 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 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. ### Previous: Basic Routing Next: More examples Edit this page --- ## Page: https://expressjs.com/en/starter/examples.html # Express examples This page contains list of examples using Express. * auth - Authentication with login and password * content-negotiation - HTTP content negotiation * cookie-sessions - Working with cookie-based sessions * cookies - Working with cookies * downloads - Transferring files to client * ejs - Working with Embedded JavaScript templating (ejs) * error-pages - Creating error pages * error - Working with error middleware * hello-world - Simple request handler * markdown - Markdown as template engine * multi-router - Working with multiple Express routers * mvc - MVC-style controllers * online - Tracking online user activity with `online` and `redis` packages * params - Working with route parameters * resource - Multiple HTTP operations on the same resource * route-map - Organizing routes using a map * route-middleware - Working with route middleware * route-separation - Organizing routes per each resource * search - Search API * session - User sessions * static-files - Serving static files * vhost - Working with virtual hosts * view-constructor - Rendering views dynamically * view-locals - Saving data in request object between middleware calls * 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 - Fullstack app with Express and Next.js using Prisma as an ORM * prisma-rest-api-ts - REST API with Express in TypeScript using Prisma as an ORM ### Previous: Static Files Next: FAQ Edit this page --- ## Page: https://expressjs.com/en/starter/faq.html # 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 * Route map * MVC style controllers Also, there are third-party extensions for Express, which simplify some of these patterns: * Resourceful routing ## 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 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. ## 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 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. ## 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 requires Node.js 0.10 or higher. * Express 5.x requires Node.js 18 or higher. ### Previous: More examples Edit this page --- ## Page: https://expressjs.com/en/guide/routing.html # Routing _Routing_ refers to how an application’s endpoints (URIs) respond to client requests. For an introduction to routing, see Basic routing. You define routing using methods of the Express `app` object that correspond to HTTP methods; for example, `app.get()` to handle GET requests and `app.post` to handle POST requests. For a full list, see app.METHOD. You can also use app.all() to handle all HTTP methods and app.use() to specify middleware as the callback function (See Using middleware for details). These routing methods specify a callback function (sometimes called “handler functions”) called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application “listens” for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function. In fact, the routing methods can have more than one callback function as arguments. With multiple callback functions, it is important to provide `next` as an argument to the callback function and then call `next()` within the body of the function to hand off control to the next callback. The following code is an example of a very basic route. const express = require('express') const app = express() // respond with "hello world" when a GET request is made to the homepage app.get('/', (req, res) => { res.send('hello world') }) ## Route methods A route method is derived from one of the HTTP methods, and is attached to an instance of the `express` class. The following code is an example of routes that are defined for the `GET` and the `POST` methods to the root of the app. // GET method route app.get('/', (req, res) => { res.send('GET request to the homepage') }) // POST method route app.post('/', (req, res) => { res.send('POST request to the homepage') }) Express supports methods that correspond to all HTTP request methods: `get`, `post`, and so on. For a full list, see app.METHOD. There is a special routing method, `app.all()`, used to load middleware functions at a path for _all_ HTTP request methods. For example, the following handler is executed for requests to the route `"/secret"` whether using `GET`, `POST`, `PUT`, `DELETE`, or any other HTTP request method supported in the http module. app.all('/secret', (req, res, next) => { console.log('Accessing the secret section ...') next() // pass control to the next handler }) ## Route paths Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions. Caution In express 5, the characters `?`, `+`, `*`, `[]`, and `()` are handled differently than in version 4, please review the migration guide for more information. Caution In express 4, regular expression characters such as `$` need to be escaped with a `\`. Note Express uses path-to-regexp for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths. Express Playground Router is a handy tool for testing basic Express routes, although it does not support pattern matching. Warning Query strings are not part of the route path. ### Route paths based on strings This route path will match requests to the root route, `/`. app.get('/', (req, res) => { res.send('root') }) This route path will match requests to `/about`. app.get('/about', (req, res) => { res.send('about') }) This route path will match requests to `/random.text`. app.get('/random.text', (req, res) => { res.send('random.text') }) ### Route paths based on string patterns Caution The string patterns in Express 5 no longer work. Please refer to the migration guide for more information. This route path will match `acd` and `abcd`. app.get('/ab?cd', (req, res) => { res.send('ab?cd') }) This route path will match `abcd`, `abbcd`, `abbbcd`, and so on. app.get('/ab+cd', (req, res) => { res.send('ab+cd') }) This route path will match `abcd`, `abxcd`, `abRANDOMcd`, `ab123cd`, and so on. app.get('/ab*cd', (req, res) => { res.send('ab*cd') }) This route path will match `/abe` and `/abcde`. app.get('/ab(cd)?e', (req, res) => { res.send('ab(cd)?e') }) ### Route paths based on regular expressions This route path will match anything with an “a” in it. app.get(/a/, (req, res) => { res.send('/a/') }) This route path will match `butterfly` and `dragonfly`, but not `butterflyman`, `dragonflyman`, and so on. app.get(/.*fly$/, (req, res) => { res.send('/.*fly$/') }) ## Route parameters Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the `req.params` object, with the name of the route parameter specified in the path as their respective keys. Route path: /users/:userId/books/:bookId Request URL: http://localhost:3000/users/34/books/8989 req.params: { "userId": "34", "bookId": "8989" } To define routes with route parameters, simply specify the route parameters in the path of the route as shown below. app.get('/users/:userId/books/:bookId', (req, res) => { res.send(req.params) }) The name of route parameters must be made up of “word characters” (\[A-Za-z0-9\_\]). Since the hyphen (`-`) and the dot (`.`) are interpreted literally, they can be used along with route parameters for useful purposes. Route path: /flights/:from-:to Request URL: http://localhost:3000/flights/LAX-SFO req.params: { "from": "LAX", "to": "SFO" } Route path: /plantae/:genus.:species Request URL: http://localhost:3000/plantae/Prunus.persica req.params: { "genus": "Prunus", "species": "persica" } Caution In express 5, Regexp characters are not supported in route paths, for more information please refer to the migration guide. To have more control over the exact string that can be matched by a route parameter, you can append a regular expression in parentheses (`()`): Route path: /user/:userId(\d+) Request URL: http://localhost:3000/user/42 req.params: {"userId": "42"} Warning Because the regular expression is usually part of a literal string, be sure to escape any `\` characters with an additional backslash, for example `\\d+`. Warning In Express 4.x, the `*` character in regular expressions is not interpreted in the usual way. As a workaround, use `{0,}` instead of `*`. This will likely be fixed in Express 5. ## Route handlers You can provide multiple callback functions that behave like middleware to handle a request. The only exception is that these callbacks might invoke `next('route')` to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route. Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples. A single callback function can handle a route. For example: app.get('/example/a', (req, res) => { res.send('Hello from A!') }) More than one callback function can handle a route (make sure you specify the `next` object). For example: app.get('/example/b', (req, res, next) => { console.log('the response will be sent by the next function ...') next() }, (req, res) => { res.send('Hello from B!') }) An array of callback functions can handle a route. For example: const cb0 = function (req, res, next) { console.log('CB0') next() } const cb1 = function (req, res, next) { console.log('CB1') next() } const cb2 = function (req, res) { res.send('Hello from C!') } app.get('/example/c', [cb0, cb1, cb2]) A combination of independent functions and arrays of functions can handle a route. For example: const cb0 = function (req, res, next) { console.log('CB0') next() } const cb1 = function (req, res, next) { console.log('CB1') next() } app.get('/example/d', [cb0, cb1], (req, res, next) => { console.log('the response will be sent by the next function ...') next() }, (req, res) => { res.send('Hello from D!') }) ## Response methods The methods on the response object (`res`) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging. | Method | Description | | --- | --- | | res.download() | Prompt a file to be downloaded. | | res.end() | End the response process. | | res.json() | Send a JSON response. | | res.jsonp() | Send a JSON response with JSONP support. | | res.redirect() | Redirect a request. | | res.render() | Render a view template. | | res.send() | Send a response of various types. | | res.sendFile() | Send a file as an octet stream. | | res.sendStatus() | Set the response status code and send its string representation as the response body. | ## app.route() You can create chainable route handlers for a route path by using `app.route()`. Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: Router() documentation. Here is an example of chained route handlers that are defined by using `app.route()`. app.route('/book') .get((req, res) => { res.send('Get a random book') }) .post((req, res) => { res.send('Add a book') }) .put((req, res) => { res.send('Update the book') }) ## express.Router Use the `express.Router` class to create modular, mountable route handlers. A `Router` instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”. The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app. Create a router file named `birds.js` in the app directory, with the following content: const express = require('express') const router = express.Router() // middleware that is specific to this router const timeLog = (req, res, next) => { console.log('Time: ', Date.now()) next() } router.use(timeLog) // define the home page route router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route router.get('/about', (req, res) => { res.send('About birds') }) module.exports = router Then, load the router module in the app: const birds = require('./birds') // ... app.use('/birds', birds) The app will now be able to handle requests to `/birds` and `/birds/about`, as well as call the `timeLog` middleware function that is specific to the route. But if the parent route `/birds` has path parameters, it will not be accessible by default from the sub-routes. To make it accessible, you will need to pass the `mergeParams` option to the Router constructor reference. const router = express.Router({ mergeParams: true }) Edit this page --- ## Page: https://expressjs.com/en/guide/writing-middleware.html # Writing middleware for use in Express apps ## Overview _Middleware_ functions are functions that have access to the request object (`req`), the response object (`res`), and the `next` function in the application’s request-response cycle. The `next` function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware. 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 in the stack. If the current middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging. The following figure shows the elements of a middleware function call: <table id="mw-fig"><tbody><tr><td id="mw-fig-imgcell"><img src="/images/express-mw.png" alt="Elements of a middleware function call" id="mw-fig-img"></td><td><div id="callout1">HTTP method for which the middleware function applies.</div><div id="callout2">Path (route) for which the middleware function applies.</div><div id="callout3">The middleware function.</div><div id="callout4">Callback argument to the middleware function, called "next" by convention.</div><div id="callout5">HTTP <a href="/en/4x/api.html#res">response</a> argument to the middleware function, called "res" by convention.</div><div id="callout6">HTTP <a href="/en/4x/api.html#req">request</a> argument to the middleware function, called "req" by convention.</div></td></tr></tbody></table> Starting with Express 5, middleware functions that return a Promise will call `next(value)` when they reject or throw an error. `next` will be called with either the rejected value or the thrown Error. ## Example Here is an example of a simple “Hello World” Express application. The remainder of this article will define and add three middleware functions to the application: one called `myLogger` that prints a simple log message, one called `requestTime` that displays the timestamp of the HTTP request, and one called `validateCookies` that validates incoming cookies. const express = require('express') const app = express() app.get('/', (req, res) => { res.send('Hello World!') }) app.listen(3000) ### Middleware function myLogger Here is a simple example of a middleware function called “myLogger”. This function just prints “LOGGED” when a request to the app passes through it. The middleware function is assigned to a variable named `myLogger`. const myLogger = function (req, res, next) { console.log('LOGGED') next() } Notice the call above to `next()`. Calling this function invokes the next middleware function in the app. The `next()` function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The `next()` function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention. To load the middleware function, call `app.use()`, specifying the middleware function. For example, the following code loads the `myLogger` middleware function before the route to the root path (/). const express = require('express') const app = express() const myLogger = function (req, res, next) { console.log('LOGGED') next() } app.use(myLogger) app.get('/', (req, res) => { res.send('Hello World!') }) app.listen(3000) Every time the app receives a request, it prints the message “LOGGED” to the terminal. The order of middleware loading is important: middleware functions that are loaded first are also executed first. If `myLogger` is loaded after the route to the root path, the request never reaches it and the app doesn’t print “LOGGED”, because the route handler of the root path terminates the request-response cycle. The middleware function `myLogger` simply prints a message, then passes on the request to the next middleware function in the stack by calling the `next()` function. ### Middleware function requestTime Next, we’ll create a middleware function called “requestTime” and add a property called `requestTime` to the request object. const requestTime = function (req, res, next) { req.requestTime = Date.now() next() } The app now uses the `requestTime` middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to `req` (the request object). const express = require('express') const app = express() const requestTime = function (req, res, next) { req.requestTime = Date.now() next() } app.use(requestTime) app.get('/', (req, res) => { let responseText = 'Hello World!<br>' responseText += `<small>Requested at: ${req.requestTime}</small>` res.send(responseText) }) app.listen(3000) When you make a request to the root of the app, the app now displays the timestamp of your request in the browser. ### Middleware function validateCookies Finally, we’ll create a middleware function that validates incoming cookies and sends a 400 response if cookies are invalid. Here’s an example function that validates cookies with an external async service. async function cookieValidator (cookies) { try { await externallyValidateCookie(cookies.testCookie) } catch { throw new Error('Invalid cookies') } } Here, we use the `cookie-parser` middleware to parse incoming cookies off the `req` object and pass them to our `cookieValidator` function. The `validateCookies` middleware returns a Promise that upon rejection will automatically trigger our error handler. const express = require('express') const cookieParser = require('cookie-parser') const cookieValidator = require('./cookieValidator') const app = express() async function validateCookies (req, res, next) { await cookieValidator(req.cookies) next() } app.use(cookieParser()) app.use(validateCookies) // error handler app.use((err, req, res, next) => { res.status(400).send(err.message) }) app.listen(3000) Note how `next()` is called after `await cookieValidator(req.cookies)`. This ensures that if `cookieValidator` resolves, the next middleware in the stack will get called. If you pass anything to the `next()` function (except the string `'route'` or `'router'`), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions. Because you have access to the request object, the response object, the next middleware function in the stack, and the whole Node.js API, the possibilities with middleware functions are endless. For more information about Express middleware, see: Using Express middleware. ## Configurable middleware If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters. File: `my-middleware.js` module.exports = function (options) { return function (req, res, next) { // Implement the middleware function based on the options object next() } } The middleware can now be used as shown below. const mw = require('./my-middleware.js') app.use(mw({ option1: '1', option2: '2' })) Refer to cookie-session and compression for examples of configurable middleware. Edit this page --- ## Page: https://expressjs.com/en/guide/using-middleware.html # Using middleware Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls. _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. If the current middleware function does not end the request-response cycle, it must call `next()` to pass control to the next middleware function. Otherwise, the request will be left hanging. An Express application can use the following types of middleware: * Application-level middleware * Router-level middleware * Error-handling middleware * Built-in middleware * Third-party middleware You can load application-level and router-level middleware with an optional mount path. You can also load a series of middleware functions together, which creates a sub-stack of the middleware system at a mount point. ## Application-level middleware Bind application-level middleware to an instance of the app object by using the `app.use()` and `app.METHOD()` functions, where `METHOD` is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase. This example shows a middleware function with no mount path. The function is executed every time the app receives a request. const express = require('express') const app = express() app.use((req, res, next) => { console.log('Time:', Date.now()) next() }) This example shows a middleware function mounted on the `/user/:id` path. The function is executed for any type of HTTP request on the `/user/:id` path. app.use('/user/:id', (req, res, next) => { console.log('Request Type:', req.method) next() }) This example shows a route and its handler function (middleware system). The function handles GET requests to the `/user/:id` path. app.get('/user/:id', (req, res, next) => { res.send('USER') }) Here is an example of loading a series of middleware functions at a mount point, with a mount path. It illustrates a middleware sub-stack that prints request info for any type of HTTP request to the `/user/:id` path. app.use('/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl) next() }, (req, res, next) => { console.log('Request Type:', req.method) next() }) Route handlers enable you to define multiple routes for a path. The example below defines two routes for GET requests to the `/user/:id` path. The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle. This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path. app.get('/user/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }, (req, res, next) => { res.send('User Info') }) // handler for the /user/:id path, which prints the user ID app.get('/user/:id', (req, res, next) => { res.send(req.params.id) }) To skip the rest of the middleware functions from a router middleware stack, call `next('route')` to pass control to the next route. Note `next('route')` will work only in middleware functions that were loaded by using the `app.METHOD()` or `router.METHOD()` functions. This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path. app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack else next() }, (req, res, next) => { // send a regular response res.send('regular') }) // handler for the /user/:id path, which sends a special response app.get('/user/:id', (req, res, next) => { res.send('special') }) Middleware can also be declared in an array for reusability. This example shows an array with a middleware sub-stack that handles GET requests to the `/user/:id` path function logOriginalUrl (req, res, next) { console.log('Request URL:', req.originalUrl) next() } function logMethod (req, res, next) { console.log('Request Type:', req.method) next() } const logStuff = [logOriginalUrl, logMethod] app.get('/user/:id', logStuff, (req, res, next) => { res.send('User Info') }) ## Router-level middleware Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of `express.Router()`. const router = express.Router() Load router-level middleware by using the `router.use()` and `router.METHOD()` functions. The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware: const express = require('express') const app = express() const router = express.Router() // a middleware function with no mount path. This code is executed for every request to the router router.use((req, res, next) => { console.log('Time:', Date.now()) next() }) // a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path router.use('/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl) next() }, (req, res, next) => { console.log('Request Type:', req.method) next() }) // a middleware sub-stack that handles GET requests to the /user/:id path router.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next router if (req.params.id === '0') next('route') // otherwise pass control to the next middleware function in this stack else next() }, (req, res, next) => { // render a regular page res.render('regular') }) // handler for the /user/:id path, which renders a special page router.get('/user/:id', (req, res, next) => { console.log(req.params.id) res.render('special') }) // mount the router on the app app.use('/', router) To skip the rest of the router’s middleware functions, call `next('router')` to pass control back out of the router instance. This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path. const express = require('express') const app = express() const router = express.Router() // predicate the router with a check and bail out when needed router.use((req, res, next) => { if (!req.headers['x-auth']) return next('router') next() }) router.get('/user/:id', (req, res) => { res.send('hello, user!') }) // use the router and 401 anything falling through app.use('/admin', router, (req, res) => { res.sendStatus(401) }) ## Error-handling middleware Error-handling middleware always takes _four_ arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the `next` object, you must specify it to maintain the signature. Otherwise, the `next` object will be interpreted as regular middleware and will fail to handle errors. Define error-handling middleware functions in the same way as other middleware functions, 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 details about error-handling middleware, see: Error handling. ## Built-in middleware Starting with version 4.x, Express no longer depends on Connect. The middleware functions that were previously included with Express are now in separate modules; see the list of middleware functions. Express has the following built-in middleware functions: * express.static serves static assets such as HTML files, images, and so on. * express.json parses incoming requests with JSON payloads. **NOTE: Available with Express 4.16.0+** * express.urlencoded parses incoming requests with URL-encoded payloads. **NOTE: Available with Express 4.16.0+** ## Third-party middleware Use third-party middleware to add functionality to Express apps. Install the Node.js module for the required functionality, then load it in your app at the application level or at the router level. The following example illustrates installing and loading the cookie-parsing middleware function `cookie-parser`. $ npm install cookie-parser const express = require('express') const app = express() const cookieParser = require('cookie-parser') // load the cookie-parsing middleware app.use(cookieParser()) For a partial list of third-party middleware functions that are commonly used with Express, see: Third-party middleware. Edit this page --- ## Page: https://expressjs.com/en/guide/overriding-express-api.html # Overriding the Express API The Express API consists of various methods and properties on the request and response objects. These are inherited by prototype. There are two extension points for the Express API: 1. The global prototypes at `express.request` and `express.response`. 2. App-specific prototypes at `app.request` and `app.response`. Altering the global prototypes will affect all loaded Express apps in the same process. If desired, alterations can be made app-specific by only altering the app-specific prototypes after creating a new app. ## Methods You can override the signature and behavior of existing methods with your own, by assigning a custom function. Following is an example of overriding the behavior of res.sendStatus. app.response.sendStatus = function (statusCode, type, message) { // code is intentionally kept simple for demonstration purpose return this.contentType(type) .status(statusCode) .send(message) } The above implementation completely changes the original signature of `res.sendStatus`. It now accepts a status code, encoding type, and the message to be sent to the client. The overridden method may now be used this way: res.sendStatus(404, 'application/json', '{"error":"resource not found"}') ## Properties Properties in the Express API are either: 1. Assigned properties (ex: `req.baseUrl`, `req.originalUrl`) 2. Defined as getters (ex: `req.secure`, `req.ip`) Since properties under category 1 are dynamically assigned on the `request` and `response` objects in the context of the current request-response cycle, their behavior cannot be overridden. Properties under category 2 can be overwritten using the Express API extensions API. The following code rewrites how the value of `req.ip` is to be derived. Now, it simply returns the value of the `Client-IP` request header. Object.defineProperty(app.request, 'ip', { configurable: true, enumerable: true, get () { return this.get('Client-IP') } }) ## Prototype In order to provide the Express API, the request/response objects passed to Express (via `app(req, res)`, for example) need to inherit from the same prototype chain. By default, this is `http.IncomingRequest.prototype` for the request and `http.ServerResponse.prototype` for the response. Unless necessary, it is recommended that this be done only at the application level, rather than globally. Also, take care that the prototype that is being used matches the functionality as closely as possible to the default prototypes. // Use FakeRequest and FakeResponse in place of http.IncomingRequest and http.ServerResponse // for the given app reference Object.setPrototypeOf(Object.getPrototypeOf(app.request), FakeRequest.prototype) Object.setPrototypeOf(Object.getPrototypeOf(app.response), FakeResponse.prototype) Edit this page --- ## Page: https://expressjs.com/en/guide/using-template-engines.html # Using template engines with Express A _template engine_ enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page. The Express application generator uses Pug as its default, but it also supports Handlebars, and EJS, among others. To render template files, set the following application setting properties, in the default `app.js` created by the generator: * `views`, the directory where the template files are located. Eg: `app.set('views', './views')`. This defaults to the `views` directory in the application root directory. * `view engine`, the template engine to use. For example, to use the Pug template engine: `app.set('view engine', 'pug')`. Then install the corresponding template engine npm package; for example to install Pug: $ npm install pug --save Express-compliant template engines such as Pug export a function named `__express(filePath, options, callback)`, which `res.render()` calls to render the template code. Some template engines do not follow this convention. The @ladjs/consolidate library follows this convention by mapping all of the popular Node.js template engines, and therefore works seamlessly within Express. After the view engine is set, you don’t have to specify the engine or load the template engine module in your app; Express loads the module internally, for example: app.set('view engine', 'pug') Then, create a Pug template file named `index.pug` in the `views` directory, with the following content: html head title= title body h1= message Create a route to render the `index.pug` file. If the `view engine` property is not set, you must specify the extension of the `view` file. Otherwise, you can omit it. app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) When you make a request to the home page, the `index.pug` file will be rendered as HTML. The view engine cache does not cache the contents of the template’s output, only the underlying template itself. The view is still re-rendered with every request even when the cache is on. Edit this page --- ## Page: https://expressjs.com/en/guide/error-handling.html # Error Handling _Error Handling_ refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler so you don’t need to write your own to get started. ## Catching Errors It’s important to ensure that Express catches all errors that occur while running route handlers and middleware. Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it. For example: app.get('/', (req, res) => { throw new Error('BROKEN') // Express will catch this on its own. }) For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the `next()` function, where Express will catch and process them. For example: app.get('/', (req, res, next) => { fs.readFile('/file-does-not-exist', (err, data) => { if (err) { next(err) // Pass errors to Express. } else { res.send(data) } }) }) Starting with Express 5, route handlers and middleware that return a Promise will call `next(value)` automatically when they reject or throw an error. For example: app.get('/user/:id', async (req, res, next) => { const user = await getUserById(req.params.id) res.send(user) }) If `getUserById` throws an error or rejects, `next` will be called with either the thrown error or the rejected value. If no rejected value is provided, `next` will be called with a default Error object provided by the Express router. If you pass anything to the `next()` function (except the string `'route'`), Express regards the current request as being an error and will skip any remaining non-error handling routing and middleware functions. If the callback in a sequence provides no data, only errors, you can simplify this code as follows: app.get('/', [ function (req, res, next) { fs.writeFile('/inaccessible-path', 'data', next) }, function (req, res) { res.send('OK') } ]) In the above example, `next` is provided as the callback for `fs.writeFile`, which is called with or without errors. If there is no error, the second handler is executed, otherwise Express catches and processes the error. You must catch errors that occur in asynchronous code invoked by route handlers or middleware and pass them to Express for processing. For example: app.get('/', (req, res, next) => { setTimeout(() => { try { throw new Error('BROKEN') } catch (err) { next(err) } }, 100) }) The above example uses a `try...catch` block to catch errors in the asynchronous code and pass them to Express. If the `try...catch` block were omitted, Express would not catch the error since it is not part of the synchronous handler code. Use promises to avoid the overhead of the `try...catch` block or when using functions that return promises. For example: app.get('/', (req, res, next) => { Promise.resolve().then(() => { throw new Error('BROKEN') }).catch(next) // Errors will be passed to Express. }) Since promises automatically catch both synchronous errors and rejected promises, you can simply provide `next` as the final catch handler and Express will catch errors, because the catch handler is given the error as the first argument. You could also use a chain of handlers to rely on synchronous error catching, by reducing the asynchronous code to something trivial. For example: app.get('/', [ function (req, res, next) { fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { res.locals.data = data next(err) }) }, function (req, res) { res.locals.data = res.locals.data.split(',')[1] res.send(res.locals.data) } ]) The above example has a couple of trivial statements from the `readFile` call. If `readFile` causes an error, then it passes the error to Express, otherwise you quickly return to the world of synchronous error handling in the next handler in the chain. Then, the example above tries to process the data. If this fails, then the synchronous error handler will catch it. If you had done this processing inside the `readFile` callback, then the application might exit and the Express error handlers would not run. Whichever method you use, if you want Express error handlers to be called in and the application to survive, you must ensure that Express receives the error. ## The default error handler Express comes with a built-in error handler that takes care of any errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack. If you pass an error to `next()` and you do not handle it in a custom error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace. The stack trace is not included in the production environment. Set the environment variable `NODE_ENV` to `production`, to run the app in production mode. When an error is written, the following information is added to the response: * The `res.statusCode` is set from `err.status` (or `err.statusCode`). If this value is outside the 4xx or 5xx range, it will be set to 500. * The `res.statusMessage` is set according to the status code. * The body will be the HTML of the status code message when in production environment, otherwise will be `err.stack`. * Any headers specified in an `err.headers` object. If you call `next()` with an error after you have started writing the response (for example, if you encounter an error while streaming the response to the client), the Express default error handler closes the connection and fails the request. So when you add a custom error handler, you must delegate to the default Express error handler, when the headers have already been sent to the client: function errorHandler (err, req, res, next) { if (res.headersSent) { return next(err) } res.status(500) res.render('error', { error: err }) } Note that the default error handler can get triggered if you call `next()` with an error in your code more than once, even if custom error handling middleware is in place. Other error handling middleware can be found at Express middleware. ## Writing error handlers Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: `(err, req, res, next)`. For example: app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Something broke!') }) You define error-handling middleware last, after other `app.use()` and routes calls; for example: const bodyParser = require('body-parser') const methodOverride = require('method-override') app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) app.use(methodOverride()) app.use((err, req, res, next) => { // logic }) Responses from within a middleware function can be in any format, such as an HTML error page, a simple message, or a JSON string. For organizational (and higher-level framework) purposes, you can define several error-handling middleware functions, much as you would with regular middleware functions. For example, to define an error-handler for requests made by using `XHR` and those without: const bodyParser = require('body-parser') const methodOverride = require('method-override') app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) app.use(methodOverride()) app.use(logErrors) app.use(clientErrorHandler) app.use(errorHandler) In this example, the generic `logErrors` might write request and error information to `stderr`, for example: function logErrors (err, req, res, next) { console.error(err.stack) next(err) } Also in this example, `clientErrorHandler` is defined as follows; in this case, the error is explicitly passed along to the next one. Notice that when _not_ calling “next” in an error-handling function, you are responsible for writing (and ending) the response. Otherwise, those requests will “hang” and will not be eligible for garbage collection. function clientErrorHandler (err, req, res, next) { if (req.xhr) { res.status(500).send({ error: 'Something failed!' }) } else { next(err) } } Implement the “catch-all” `errorHandler` function as follows (for example): function errorHandler (err, req, res, next) { res.status(500) res.render('error', { error: err }) } If you have a route handler with multiple callback functions, you can use the `route` parameter to skip to the next route handler. For example: app.get('/a_route_behind_paywall', (req, res, next) => { if (!req.user.hasPaid) { // continue handling this request next('route') } else { next() } }, (req, res, next) => { PaidContent.find((err, doc) => { if (err) return next(err) res.json(doc) }) }) In this example, the `getPaidContent` handler will be skipped but any remaining handlers in `app` for `/a_route_behind_paywall` would continue to be executed. Calls to `next()` and `next(err)` indicate that the current handler is complete and in what state. `next(err)` will skip all remaining handlers in the chain except for those that are set up to handle errors as described above. Edit this page --- ## Page: https://expressjs.com/en/guide/debugging.html # Debugging Express To see all the internal logs used in Express, set the `DEBUG` environment variable to `express:*` when launching your app. $ DEBUG=express:* node index.js On Windows, use the corresponding command. > $env:DEBUG = "express:*"; node index.js Running this command on the default app generated by the express generator prints the following output: $ DEBUG=express:* node ./bin/www express:router:route new / +0ms express:router:layer new / +1ms express:router:route get / +1ms express:router:layer new / +0ms express:router:route new / +1ms express:router:layer new / +0ms express:router:route get / +0ms express:router:layer new / +0ms express:application compile etag weak +1ms express:application compile query parser extended +0ms express:application compile trust proxy false +0ms express:application booting in development mode +1ms express:router use / query +0ms express:router:layer new / +0ms express:router use / expressInit +0ms express:router:layer new / +0ms express:router use / favicon +1ms express:router:layer new / +0ms express:router use / logger +0ms express:router:layer new / +0ms express:router use / jsonParser +0ms express:router:layer new / +1ms express:router use / urlencodedParser +0ms express:router:layer new / +0ms express:router use / cookieParser +0ms express:router:layer new / +0ms express:router use / stylus +90ms express:router:layer new / +0ms express:router use / serveStatic +0ms express:router:layer new / +0ms express:router use / router +0ms express:router:layer new / +1ms express:router use /users router +0ms express:router:layer new /users +0ms express:router use / <anonymous> +0ms express:router:layer new / +0ms express:router use / <anonymous> +0ms express:router:layer new / +0ms express:router use / <anonymous> +0ms express:router:layer new / +0ms When a request is then made to the app, you will see the logs specified in the Express code: express:router dispatching GET / +4h express:router query : / +2ms express:router expressInit : / +0ms express:router favicon : / +0ms express:router logger : / +1ms express:router jsonParser : / +0ms express:router urlencodedParser : / +1ms express:router cookieParser : / +0ms express:router stylus : / +0ms express:router serveStatic : / +2ms express:router router : / +2ms express:router dispatching GET / +1ms express:view lookup "index.pug" +338ms express:view stat "/projects/example/views/index.pug" +0ms express:view render "/projects/example/views/index.pug" +1ms To see the logs only from the router implementation, set the value of `DEBUG` to `express:router`. Likewise, to see logs only from the application implementation, set the value of `DEBUG` to `express:application`, and so on. ## Applications generated by `express` An application generated by the `express` command uses the `debug` module and its debug namespace is scoped to the name of the application. For example, if you generated the app with `$ express sample-app`, you can enable the debug statements with the following command: $ DEBUG=sample-app:* node ./bin/www You can specify more than one debug namespace by assigning a comma-separated list of names: $ DEBUG=http,mail,express:* node index.js ## Advanced options When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | | --- | --- | | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_COLORS` | Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_FD` | File descriptor to write debug output to. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | Note The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for `util.inspect()` for the complete list. Edit this page --- ## Page: https://expressjs.com/en/guide/behind-proxies.html # Express behind proxies When running an Express app behind a reverse proxy, some of the Express APIs may return different values than expected. In order to adjust for this, the `trust proxy` application setting may be used to expose information provided by the reverse proxy in the Express APIs. The most common issue is express APIs that expose the client’s IP address may instead show an internal IP address of the reverse proxy. When configuring the `trust proxy` setting, it is important to understand the exact setup of the reverse proxy. Since this setting will trust values provided in the request, it is important that the combination of the setting in Express matches how the reverse proxy operates. The application setting `trust proxy` may be set to one of the values listed in the following table. | Type | Value | | --- | --- | | Boolean | If `true`, the client’s IP address is understood as the left-most entry in the `X-Forwarded-For` header. If `false`, the app is understood as directly facing the client and the client’s IP address is derived from `req.socket.remoteAddress`. This is the default setting. When setting to `true`, it is important to ensure that the last reverse proxy trusted is removing/overwriting all of the following HTTP headers: `X-Forwarded-For`, `X-Forwarded-Host`, and `X-Forwarded-Proto`, otherwise it may be possible for the client to provide any value. | | IP addresses | An IP address, subnet, or an array of IP addresses and subnets to trust as being a reverse proxy. The following list shows the pre-configured subnet names: * loopback - `127.0.0.1/8`, `::1/128` * linklocal - `169.254.0.0/16`, `fe80::/10` * uniquelocal - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `fc00::/7` You can set IP addresses in any of the following ways: app.set('trust proxy', 'loopback') // specify a single subnet app.set('trust proxy', 'loopback, 123.123.123.123') // specify a subnet and an address app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple subnets as CSV app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client’s IP address. This works by checking if `req.socket.remoteAddress` is trusted. If so, then each address in `X-Forwarded-For` is checked from right to left until the first non-trusted address. | | Number | Use the address that is at most `n` number of hops away from the Express application. `req.socket.remoteAddress` is the first hop, and the rest are looked for in the `X-Forwarded-For` header from right to left. A value of `0` means that the first untrusted address would be `req.socket.remoteAddress`, i.e. there is no reverse proxy. When using this setting, it is important to ensure there are not multiple, different-length paths to the Express application such that the client can be less than the configured number of hops away, otherwise it may be possible for the client to provide any value. | | Function | Custom trust implementation. app.set('trust proxy', (ip) => { if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs else return false }) | Enabling `trust proxy` will have the following impact: * The value of req.hostname is derived from the value set in the `X-Forwarded-Host` header, which can be set by the client or by the proxy. * `X-Forwarded-Proto` can be set by the reverse proxy to tell the app whether it is `https` or `http` or even an invalid name. This value is reflected by req.protocol. * The req.ip and req.ips values are populated based on the socket address and `X-Forwarded-For` header, starting at the first untrusted address. The `trust proxy` setting is implemented using the proxy-addr package. For more information, see its documentation. Edit this page --- ## Page: https://expressjs.com/en/guide/migrating-4.html # Moving to Express 4 ## Overview Express 4 is a breaking change from Express 3. That means an existing Express 3 app will _not_ work if you update the Express version in its dependencies. This article covers: * Changes in Express 4. * An example of migrating an Express 3 app to Express 4. * Upgrading to the Express 4 app generator. ## Changes in Express 4 There are several significant changes in Express 4: * Changes to Express core and middleware system. The dependencies on Connect and built-in middleware were removed, so you must add middleware yourself. * Changes to the routing system. * Various other changes. See also: * New features in 4.x. * Migrating from 3.x to 4.x. ### Changes to Express core and middleware system Express 4 no longer depends on Connect, and removes all built-in middleware from its core, except for the `express.static` function. This means that Express is now an independent routing and middleware web framework, and Express versioning and releases are not affected by middleware updates. Without built-in middleware, you must explicitly add all the middleware that is required to run your app. Simply follow these steps: 1. Install the module: `npm install --save <module-name>` 2. In your app, require the module: `require('module-name')` 3. Use the module according to its documentation: `app.use( ... )` The following table lists Express 3 middleware and their counterparts in Express 4. | Express 3 | Express 4 | | --- | --- | | `express.bodyParser` | body-parser + multer | | `express.compress` | compression | | `express.cookieSession` | cookie-session | | `express.cookieParser` | cookie-parser | | `express.logger` | morgan | | `express.session` | express-session | | `express.favicon` | serve-favicon | | `express.responseTime` | response-time | | `express.errorHandler` | errorhandler | | `express.methodOverride` | method-override | | `express.timeout` | connect-timeout | | `express.vhost` | vhost | | `express.csrf` | csurf | | `express.directory` | serve-index | | `express.static` | serve-static | Here is the complete list of Express 4 middleware. In most cases, you can simply replace the old version 3 middleware with its Express 4 counterpart. For details, see the module documentation in GitHub. #### `app.use` accepts parameters In version 4 you can use a variable parameter to define the path where middleware functions are loaded, then read the value of the parameter from the route handler. For example: app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) ### The routing system Apps now implicitly load routing middleware, so you no longer have to worry about the order in which middleware is loaded with respect to the `router` middleware. The way you define routes is unchanged, but the routing system has two new features to help organize your routes: * A new method, `app.route()`, to create chainable route handlers for a route path. * A new class, `express.Router`, to create modular mountable route handlers. #### `app.route()` method The new `app.route()` method enables you to create chainable route handlers for a route path. Because the path is specified in a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see `Router()` documentation. Here is an example of chained route handlers that are defined by using the `app.route()` function. app.route('/book') .get((req, res) => { res.send('Get a random book') }) .post((req, res) => { res.send('Add a book') }) .put((req, res) => { res.send('Update the book') }) #### `express.Router` class The other feature that helps to organize routes is a new class, `express.Router`, that you can use to create modular mountable route handlers. A `Router` instance is a complete middleware and routing system; for this reason it is often referred to as a “mini-app”. The following example creates a router as a module, loads middleware in it, defines some routes, and mounts it on a path on the main app. For example, create a router file named `birds.js` in the app directory, with the following content: var express = require('express') var router = express.Router() // middleware specific to this router router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route router.get('/about', (req, res) => { res.send('About birds') }) module.exports = router Then, load the router module in the app: var birds = require('./birds') // ... app.use('/birds', birds) The app will now be able to handle requests to the `/birds` and `/birds/about` paths, and will call the `timeLog` middleware that is specific to the route. ### Other changes The following table lists other small but important changes in Express 4: | Object | Description | | --- | --- | | Node.js | Express 4 requires Node.js 0.10.x or later and has dropped support for Node.js 0.8.x. | | `http.createServer()` | The `http` module is no longer needed, unless you need to directly work with it (socket.io/SPDY/HTTPS). The app can be started by using the `app.listen()` function. | | `app.configure()` | The `app.configure()` function has been removed. Use the `process.env.NODE_ENV` or `app.get('env')` function to detect the environment and configure the app accordingly. | | `json spaces` | The `json spaces` application property is disabled by default in Express 4. | | `req.accepted()` | Use `req.accepts()`, `req.acceptsEncodings()`, `req.acceptsCharsets()`, and `req.acceptsLanguages()`. | | `res.location()` | No longer resolves relative URLs. | | `req.params` | Was an array; now an object. | | `res.locals` | Was a function; now an object. | | `res.headerSent` | Changed to `res.headersSent`. | | `app.route` | Now available as `app.mountpath`. | | `res.on('header')` | Removed. | | `res.charset` | Removed. | | `res.setHeader('Set-Cookie', val)` | Functionality is now limited to setting the basic cookie value. Use `res.cookie()` for added functionality. | ## Example app migration Here is an example of migrating an Express 3 application to Express 4. The files of interest are `app.js` and `package.json`. ### Version 3 app #### `app.js` Consider an Express v.3 application with the following `app.js` file: var express = require('express') var routes = require('./routes') var user = require('./routes/user') var http = require('http') var path = require('path') var app = express() // all environments app.set('port', process.env.PORT || 3000) app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'pug') app.use(express.favicon()) app.use(express.logger('dev')) app.use(express.methodOverride()) app.use(express.session({ secret: 'your secret here' })) app.use(express.bodyParser()) app.use(app.router) app.use(express.static(path.join(__dirname, 'public'))) // development only if (app.get('env') === 'development') { app.use(express.errorHandler()) } app.get('/', routes.index) app.get('/users', user.list) http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) #### `package.json` The accompanying version 3 `package.json` file might look something like this: { "name": "application-name", "version": "0.0.1", "private": true, "scripts": { "start": "node app.js" }, "dependencies": { "express": "3.12.0", "pug": "*" } } ### Process Begin the migration process by installing the required middleware for the Express 4 app and updating Express and Pug to their respective latest version with the following command: $ npm install serve-favicon morgan method-override express-session body-parser multer errorhandler express@latest pug@latest --save Make the following changes to `app.js`: 1. The built-in Express middleware functions `express.favicon`, `express.logger`, `express.methodOverride`, `express.session`, `express.bodyParser` and `express.errorHandler` are no longer available on the `express` object. You must install their alternatives manually and load them in the app. 2. You no longer need to load the `app.router` function. It is not a valid Express 4 app object, so remove the `app.use(app.router);` code. 3. Make sure that the middleware functions are loaded in the correct order - load `errorHandler` after loading the app routes. ### Version 4 app #### `package.json` Running the above `npm` command will update `package.json` as follows: { "name": "application-name", "version": "0.0.1", "private": true, "scripts": { "start": "node app.js" }, "dependencies": { "body-parser": "^1.5.2", "errorhandler": "^1.1.1", "express": "^4.8.0", "express-session": "^1.7.2", "pug": "^2.0.0", "method-override": "^2.1.2", "morgan": "^1.2.2", "multer": "^0.1.3", "serve-favicon": "^2.0.1" } } #### `app.js` Then, remove invalid code, load the required middleware, and make other changes as necessary. The `app.js` file will look like this: var http = require('http') var express = require('express') var routes = require('./routes') var user = require('./routes/user') var path = require('path') var favicon = require('serve-favicon') var logger = require('morgan') var methodOverride = require('method-override') var session = require('express-session') var bodyParser = require('body-parser') var multer = require('multer') var errorHandler = require('errorhandler') var app = express() // all environments app.set('port', process.env.PORT || 3000) app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'pug') app.use(favicon(path.join(__dirname, '/public/favicon.ico'))) app.use(logger('dev')) app.use(methodOverride()) app.use(session({ resave: true, saveUninitialized: true, secret: 'uwotm8' })) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(multer()) app.use(express.static(path.join(__dirname, 'public'))) app.get('/', routes.index) app.get('/users', user.list) // error handling middleware should be loaded after the loading the routes if (app.get('env') === 'development') { app.use(errorHandler()) } var server = http.createServer(app) server.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS), loading it is not required, and the app can be simply started this way: app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ### Run the app The migration process is complete, and the app is now an Express 4 app. To confirm, start the app by using the following command: $ node . Load http://localhost:3000 and see the home page being rendered by Express 4. ## Upgrading to the Express 4 app generator The command-line tool to generate an Express app is still `express`, but to upgrade to the new version, you must uninstall the Express 3 app generator and then install the new `express-generator`. ### Installing If you already have the Express 3 app generator installed on your system, you must uninstall it: $ npm uninstall -g express Depending on how your file and directory privileges are configured, you might need to run this command with `sudo`. Now install the new generator: $ npm install -g express-generator Depending on how your file and directory privileges are configured, you might need to run this command with `sudo`. Now the `express` command on your system is updated to the Express 4 generator. ### Changes to the app generator Command options and use largely remain the same, with the following exceptions: * Removed the `--sessions` option. * Removed the `--jshtml` option. * Added the `--hogan` option to support Hogan.js. ### Example Execute the following command to create an Express 4 app: $ express app4 If you look at the contents of the `app4/app.js` file, you will notice that all the middleware functions (except `express.static`) that are required for the app are loaded as independent modules, and the `router` middleware is no longer explicitly loaded in the app. You will also notice that the `app.js` file is now a Node.js module, in contrast to the standalone app that was generated by the old generator. After installing the dependencies, start the app by using the following command: $ npm start If you look at the `npm start` script in the `package.json` file, you will notice that the actual command that starts the app is `node ./bin/www`, which used to be `node app.js` in Express 3. Because the `app.js` file that was generated by the Express 4 generator is now a Node.js module, it can no longer be started independently as an app (unless you modify the code). The module must be loaded in a Node.js file and started via the Node.js file. The Node.js file is `./bin/www` in this case. Neither the `bin` directory nor the extensionless `www` file is mandatory for creating an Express app or starting the app. They are just suggestions made by the generator, so feel free to modify them to suit your needs. To get rid of the `www` directory and keep things the “Express 3 way”, delete the line that says `module.exports = app;` at the end of the `app.js` file, then paste the following code in its place: app.set('port', process.env.PORT || 3000) var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) Ensure that you load the `debug` module at the top of the `app.js` file by using the following code: var debug = require('debug')('app4') Next, change `"start": "node ./bin/www"` in the `package.json` file to `"start": "node app.js"`. You have now moved the functionality of `./bin/www` back to `app.js`. This change is not recommended, but the exercise helps you to understand how the `./bin/www` file works, and why the `app.js` file no longer starts on its own. Edit this page --- ## Page: https://expressjs.com/en/guide/migrating-5.html # Moving to Express 5 ## Overview Express 5 is not very different from Express 4; although it maintains the same basic API, there are still changes that break compatibility with the previous version. Therefore, an application built with Express 4 might not work if you update it to use Express 5. To install this version, you need to have a Node.js version 18 or higher. Then, execute the following command in your application directory: npm install "express@5" You can then run your automated tests to see what fails, and fix problems according to the updates listed below. After addressing test failures, run your app to see what errors occur. You’ll find out right away if the app uses any methods or properties that are not supported. ## Express 5 Codemods To help you migrate your express server, we have created a set of codemods that will help you automatically update your code to the latest version of Express. Run the following command for run all the codemods available: npx @expressjs/codemod upgrade If you want to run a specific codemod, you can run the following command: npx @expressjs/codemod name-of-the-codemod You can find the list of available codemods here. ## Changes in Express 5 **Removed methods and properties** * app.del() * app.param(fn) * Pluralized method names * Leading colon in name argument to app.param(name, fn) * req.param(name) * res.json(obj, status) * res.jsonp(obj, status) * res.redirect('back') and res.location('back') * res.redirect(url, status) * res.send(body, status) * res.send(status) * res.sendfile() * router.param(fn) * express.static.mime * express:router debug logs **Changed** * Path route matching syntax * Rejected promises handled from middleware and handlers * express.urlencoded * app.listen * app.router * req.body * req.host * req.query * res.clearCookie * res.status * res.vary **Improvements** * res.render() * Brotli encoding support ## Removed methods and properties If you use any of these methods or properties in your app, it will crash. So, you’ll need to change your app after you update to version 5. ### app.del() Express 5 no longer supports the `app.del()` function. If you use this function, an error is thrown. For registering HTTP DELETE routes, use the `app.delete()` function instead. Initially, `del` was used instead of `delete`, because `delete` is a reserved keyword in JavaScript. However, as of ECMAScript 6, `delete` and other reserved keywords can legally be used as property names. Note You can replace the deprecated signatures with the following command: npx @expressjs/codemod v4-deprecated-signatures // v4 app.del('/user/:id', (req, res) => { res.send(`DELETE /user/${req.params.id}`) }) // v5 app.delete('/user/:id', (req, res) => { res.send(`DELETE /user/${req.params.id}`) }) ### app.param(fn) The `app.param(fn)` signature was used for modifying the behavior of the `app.param(name, fn)` function. It has been deprecated since v4.11.0, and Express 5 no longer supports it at all. ### Pluralized method names The following method names have been pluralized. In Express 4, using the old methods resulted in a deprecation warning. Express 5 no longer supports them at all: `req.acceptsCharset()` is replaced by `req.acceptsCharsets()`. `req.acceptsEncoding()` is replaced by `req.acceptsEncodings()`. `req.acceptsLanguage()` is replaced by `req.acceptsLanguages()`. Note You can replace the deprecated signatures with the following command: npx @expressjs/codemod pluralized-methods // v4 app.all('/', (req, res) => { req.acceptsCharset('utf-8') req.acceptsEncoding('br') req.acceptsLanguage('en') // ... }) // v5 app.all('/', (req, res) => { req.acceptsCharsets('utf-8') req.acceptsEncodings('br') req.acceptsLanguages('en') // ... }) ### Leading colon (:) in the name for app.param(name, fn) A leading colon character (:) in the name for the `app.param(name, fn)` function is a remnant of Express 3, and for the sake of backwards compatibility, Express 4 supported it with a deprecation notice. Express 5 will silently ignore it and use the name parameter without prefixing it with a colon. This should not affect your code if you follow the Express 4 documentation of app.param, as it makes no mention of the leading colon. ### req.param(name) This potentially confusing and dangerous method of retrieving form data has been removed. You will now need to specifically look for the submitted parameter name in the `req.params`, `req.body`, or `req.query` object. Note You can replace the deprecated signatures with the following command: npx @expressjs/codemod req-param // v4 app.post('/user', (req, res) => { const id = req.param('id') const body = req.param('body') const query = req.param('query') // ... }) // v5 app.post('/user', (req, res) => { const id = req.params.id const body = req.body const query = req.query // ... }) ### res.json(obj, status) Express 5 no longer supports the signature `res.json(obj, status)`. Instead, set the status and then chain it to the `res.json()` method like this: `res.status(status).json(obj)`. Note You can replace the deprecated signatures with the following command: npx @expressjs/codemod v4-deprecated-signatures // v4 app.post('/user', (req, res) => { res.json({ name: 'Ruben' }, 201) }) // v5 app.post('/user', (req, res) => { res.status(201).json({ name: 'Ruben' }) }) ### res.jsonp(obj, status) Express 5 no longer supports the signature `res.jsonp(obj, status)`. Instead, set the status and then chain it to the `res.jsonp()` method like this: `res.status(status).jsonp(obj)`. Note You can replace the deprecated signatures with the following command: npx @expressjs/codemod v4-deprecated-signatures // v4 app.post('/user', (req, res) => { res.jsonp({ name: 'Ruben' }, 201) }) // v5 app.post('/user', (req, res) => { res.status(201).jsonp({ name: 'Ruben' }) }) ### res.redirect(url, status) Express 5 no longer supports the signature `res.redirect(url, status)`. Instead, use the following signature: `res.redirect(status, url)`. Note You can replace the deprecated signatures with the following command: npx @expressjs/codemod v4-deprecated-signatures // v4 app.get('/user', (req, res) => { res.redirect('/users', 301) }) // v5 app.get('/user', (req, res) => { res.redirect(301, '/users') }) ### res.redirect('back') and res.location('back') Express 5 no longer supports the magic string `back` in the `res.redirect()` and `res.location()` methods. Instead, use the `req.get('Referrer') || '/'` value to redirect back to the previous page. In Express 4, the res.`redirect('back')` and `res.location('back')` methods were deprecated. Note You can replace the deprecated signatures with the following command: npx @expressjs/codemod magic-redirect // v4 app.get('/user', (req, res) => { res.redirect('back') }) // v5 app.get('/user', (req, res) => { res.redirect(req.get('Referrer') || '/') }) ### res.send(body, status) Express 5 no longer supports the signature `res.send(obj, status)`. Instead, set the status and then chain it to the `res.send()` method like this: `res.status(status).send(obj)`. Note You can replace the deprecated signatures with the following command: npx @expressjs/codemod v4-deprecated-signatures // v4 app.get('/user', (req, res) => { res.send({ name: 'Ruben' }, 200) }) // v5 app.get('/user', (req, res) => { res.status(200).send({ name: 'Ruben' }) }) ### res.send(status) Express 5 no longer supports the signature `res.send(status)`, where `status` is a number. Instead, use the `res.sendStatus(statusCode)` function, which sets the HTTP response header status code and sends the text version of the code: “Not Found”, “Internal Server Error”, and so on. If you need to send a number by using the `res.send()` function, quote the number to convert it to a string, so that Express does not interpret it as an attempt to use the unsupported old signature. Note You can replace the deprecated signatures with the following command: npx @expressjs/codemod v4-deprecated-signatures // v4 app.get('/user', (req, res) => { res.send(200) }) // v5 app.get('/user', (req, res) => { res.sendStatus(200) }) ### res.sendfile() The `res.sendfile()` function has been replaced by a camel-cased version `res.sendFile()` in Express 5. Note You can replace the deprecated signatures with the following command: npx @expressjs/codemod v4-deprecated-signatures // v4 app.get('/user', (req, res) => { res.sendfile('/path/to/file') }) // v5 app.get('/user', (req, res) => { res.sendFile('/path/to/file') }) ### router.param(fn) The `router.param(fn)` signature was used for modifying the behavior of the `router.param(name, fn)` function. It has been deprecated since v4.11.0, and Express 5 no longer supports it at all. ### express.static.mime In Express 5, `mime` is no longer an exported property of the `static` field. Use the `mime-types` package to work with MIME type values. // v4 express.static.mime.lookup('json') // v5 const mime = require('mime-types') mime.lookup('json') ### express:router debug logs In Express 5, router handling logic is performed by a dependency. Therefore, the debug logs for the router are no longer available under the `express:` namespace. In v4, the logs were available under the namespaces `express:router`, `express:router:layer`, and `express:router:route`. All of these were included under the namespace `express:*`. In v5.1+, the logs are available under the namespaces `router`, `router:layer`, and `router:route`. The logs from `router:layer` and `router:route` are included in the namespace `router:*`. To achieve the same detail of debug logging when using `express:*` in v4, use a conjunction of `express:*`, `router`, and `router:*`. # v4 DEBUG=express:* node index.js # v5 DEBUG=express:*,router,router:* node index.js ## Changed ### Path route matching syntax Path route matching syntax is when a string is supplied as the first parameter to the `app.all()`, `app.use()`, `app.METHOD()`, `router.all()`, `router.METHOD()`, and `router.use()` APIs. The following changes have been made to how the path string is matched to an incoming request: * The wildcard `*` must have a name, matching the behavior of parameters `:`, use `/*splat` instead of `/*` // v4 app.get('/*', async (req, res) => { res.send('ok') }) // v5 app.get('/*splat', async (req, res) => { res.send('ok') }) Note `*splat` matches any path without the root path. If you need to match the root path as well `/`, you can use `/{*splat}`, wrapping the wildcard in braces. // v5 app.get('/{*splat}', async (req, res) => { res.send('ok') }) * The optional character `?` is no longer supported, use braces instead. // v4 app.get('/:file.:ext?', async (req, res) => { res.send('ok') }) // v5 app.get('/:file{.:ext}', async (req, res) => { res.send('ok') }) * Regexp characters are not supported. For example: app.get('/[discussion|page]/:slug', async (req, res) => { res.status(200).send('ok') }) should be changed to: app.get(['/discussion/:slug', '/page/:slug'], async (req, res) => { res.status(200).send('ok') }) * Some characters have been reserved to avoid confusion during upgrade (`()[]?+!`), use `\` to escape them. * Parameter names now support valid JavaScript identifiers, or quoted like `:"this"`. ### Rejected promises handled from middleware and handlers Request middleware and handlers that return rejected promises are now handled by forwarding the rejected value as an `Error` to the error handling middleware. This means that using `async` functions as middleware and handlers are easier than ever. When an error is thrown in an `async` function or a rejected promise is `await`ed inside an async function, those errors will be passed to the error handler as if calling `next(err)`. Details of how Express handles errors is covered in the error handling documentation. ### express.urlencoded The `express.urlencoded` method makes the `extended` option `false` by default. ### app.listen In Express 5, the `app.listen` method will invoke the user-provided callback function (if provided) when the server receives an error event. In Express 4, such errors would be thrown. This change shifts error-handling responsibility to the callback function in Express 5. If there is an error, it will be passed to the callback as an argument. For example: const server = app.listen(8080, '0.0.0.0', (error) => { if (error) { throw error // e.g. EADDRINUSE } console.log(`Listening on ${JSON.stringify(server.address())}`) }) ### app.router The `app.router` object, which was removed in Express 4, has made a comeback in Express 5. In the new version, this object is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it. ### req.body The `req.body` property returns `undefined` when the body has not been parsed. In Express 4, it returns `{}` by default. ### req.host In Express 4, the `req.host` function incorrectly stripped off the port number if it was present. In Express 5, the port number is maintained. ### req.query The `req.query` property is no longer a writable property and is instead a getter. The default query parser has been changed from “extended” to “simple”. ### res.clearCookie The `res.clearCookie` method ignores the `maxAge` and `expires` options provided by the user. ### res.status The `res.status` method only accepts integers in the range of `100` to `999`, following the behavior defined by Node.js, and it returns an error when the status code is not an integer. ### res.vary The `res.vary` throws an error when the `field` argument is missing. In Express 4, if the argument was omitted, it gave a warning in the console ## Improvements ### res.render() This method now enforces asynchronous behavior for all view engines, avoiding bugs caused by view engines that had a synchronous implementation and that violated the recommended interface. ### Brotli encoding support Express 5 supports Brotli encoding for requests received from clients that support it. Edit this page --- ## Page: https://expressjs.com/en/guide/database-integration.html # Database integration Adding the capability to connect databases to Express apps is just a matter of loading an appropriate Node.js driver for the database in your app. This document briefly explains how to add and use some of the most popular Node.js modules for database systems in your Express app: * Cassandra * Couchbase * CouchDB * LevelDB * MySQL * MongoDB * Neo4j * Oracle * PostgreSQL * Redis * SQL Server * SQLite * Elasticsearch These database drivers are among many that are available. For other options, search on the npm site. ## Cassandra **Module**: cassandra-driver ### Installation $ npm install cassandra-driver ### Example const cassandra = require('cassandra-driver') const client = new cassandra.Client({ contactPoints: ['localhost'] }) client.execute('select key from system.local', (err, result) => { if (err) throw err console.log(result.rows[0]) }) ## Couchbase **Module**: couchnode ### Installation $ npm install couchbase ### Example const couchbase = require('couchbase') const bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName') // add a document to a bucket bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => { if (err) { console.log(err) } else { console.log(result) } }) // get all documents with shoe size 13 const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1' const query = N1qlQuery.fromString(n1ql) bucket.query(query, [13], (err, result) => { if (err) { console.log(err) } else { console.log(result) } }) ## CouchDB **Module**: nano ### Installation $ npm install nano ### Example const nano = require('nano')('http://localhost:5984') nano.db.create('books') const books = nano.db.use('books') // Insert a book document in the books database books.insert({ name: 'The Art of war' }, null, (err, body) => { if (err) { console.log(err) } else { console.log(body) } }) // Get a list of all books books.list((err, body) => { if (err) { console.log(err) } else { console.log(body.rows) } }) ## LevelDB **Module**: levelup ### Installation $ npm install level levelup leveldown ### Example const levelup = require('levelup') const db = levelup('./mydb') db.put('name', 'LevelUP', (err) => { if (err) return console.log('Ooops!', err) db.get('name', (err, value) => { if (err) return console.log('Ooops!', err) console.log(`name=${value}`) }) }) ## MySQL **Module**: mysql ### Installation $ npm install mysql ### Example const mysql = require('mysql') const connection = mysql.createConnection({ host: 'localhost', user: 'dbuser', password: 's3kreee7', database: 'my_db' }) connection.connect() connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => { if (err) throw err console.log('The solution is: ', rows[0].solution) }) connection.end() ## MongoDB **Module**: mongodb ### Installation $ npm install mongodb ### Example (v2.\*) const MongoClient = require('mongodb').MongoClient MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { if (err) throw err db.collection('mammals').find().toArray((err, result) => { if (err) throw err console.log(result) }) }) ### Example (v3.\*) const MongoClient = require('mongodb').MongoClient MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { if (err) throw err const db = client.db('animals') db.collection('mammals').find().toArray((err, result) => { if (err) throw err console.log(result) }) }) If you want an object model driver for MongoDB, look at Mongoose. ## Neo4j **Module**: neo4j-driver ### Installation $ npm install neo4j-driver ### Example const neo4j = require('neo4j-driver') const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', 'letmein')) const session = driver.session() session.readTransaction((tx) => { return tx.run('MATCH (n) RETURN count(n) AS count') .then((res) => { console.log(res.records[0].get('count')) }) .catch((error) => { console.log(error) }) }) ## Oracle **Module**: oracledb ### Installation NOTE: See installation prerequisites. $ npm install oracledb ### Example const oracledb = require('oracledb') const config = { user: '<your db user>', password: '<your db password>', connectString: 'localhost:1521/orcl' } async function getEmployee (empId) { let conn try { conn = await oracledb.getConnection(config) const result = await conn.execute( 'select * from employees where employee_id = :id', [empId] ) console.log(result.rows[0]) } catch (err) { console.log('Ouch!', err) } finally { if (conn) { // conn assignment worked, need to close await conn.close() } } } getEmployee(101) ## PostgreSQL **Module**: pg-promise ### Installation $ npm install pg-promise ### Example const pgp = require('pg-promise')(/* options */) const db = pgp('postgres://username:password@host:port/database') db.one('SELECT $1 AS value', 123) .then((data) => { console.log('DATA:', data.value) }) .catch((error) => { console.log('ERROR:', error) }) ## Redis **Module**: redis ### Installation $ npm install redis ### Example const redis = require('redis') const client = redis.createClient() client.on('error', (err) => { console.log(`Error ${err}`) }) client.set('string key', 'string val', redis.print) client.hset('hash key', 'hashtest 1', 'some value', redis.print) client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print) client.hkeys('hash key', (err, replies) => { console.log(`${replies.length} replies:`) replies.forEach((reply, i) => { console.log(` ${i}: ${reply}`) }) client.quit() }) ## SQL Server **Module**: tedious ### Installation $ npm install tedious ### Example const Connection = require('tedious').Connection const Request = require('tedious').Request const config = { server: 'localhost', authentication: { type: 'default', options: { userName: 'your_username', // update me password: 'your_password' // update me } } } const connection = new Connection(config) connection.on('connect', (err) => { if (err) { console.log(err) } else { executeStatement() } }) function executeStatement () { request = new Request("select 123, 'hello world'", (err, rowCount) => { if (err) { console.log(err) } else { console.log(`${rowCount} rows`) } connection.close() }) request.on('row', (columns) => { columns.forEach((column) => { if (column.value === null) { console.log('NULL') } else { console.log(column.value) } }) }) connection.execSql(request) } ## SQLite **Module**: sqlite3 ### Installation $ npm install sqlite3 ### Example const sqlite3 = require('sqlite3').verbose() const db = new sqlite3.Database(':memory:') db.serialize(() => { db.run('CREATE TABLE lorem (info TEXT)') const stmt = db.prepare('INSERT INTO lorem VALUES (?)') for (let i = 0; i < 10; i++) { stmt.run(`Ipsum ${i}`) } stmt.finalize() db.each('SELECT rowid AS id, info FROM lorem', (err, row) => { console.log(`${row.id}: ${row.info}`) }) }) db.close() ## Elasticsearch **Module**: elasticsearch ### Installation $ npm install elasticsearch ### Example const elasticsearch = require('elasticsearch') const client = elasticsearch.Client({ host: 'localhost:9200' }) client.search({ index: 'books', type: 'book', body: { query: { multi_match: { query: 'express js', fields: ['title', 'description'] } } } }).then((response) => { const hits = response.hits.hits }, (error) => { console.trace(error.message) }) Edit this page