# Express Best Practices Learn best development practices for [Express][express] web applications. **You will need** - A working [Express][express] application **Recommended reading** - [Express](../express/) - [Mongoose](../mongoose/) --- ## Use environment variables for configuration .breadcrumbs[
Express Best Practices
] Never hardcode configuration into your application, as it makes it difficult to deploy in different environments. You may also unintentionally expose sensitive data such as secret keys. [Environment variables][node-process-env] are a suitable alternative. There is already an example in the `bin/start.js` file of the Express starter application: ```js const port = process.env.PORT ?? 3000; ``` That line is equivalent to the following code: ```js let port; if (process.env.PORT !== undefined) { port = process.env.PORT; } else { port = 3000; } ``` --- ### Running your application with environment variables .breadcrumbs[
Express Best Practices
>
Use environment variables for configuration
] Assuming this is the command to run your application: ```bash $> npm start ``` In a Bash shell, you can prefix it with any environment variable(s) you may want to set: ```bash $> PORT=4000 FOO=bar npm start ``` You can also set them with `export` for the remainder of your Bash session, before running your application: ```bash $> export PORT=4000 $> export FOO=bar $> npm start ``` > On a server or in a cloud environment, you want to edit the process manager's > or cloud platform's configuration for your application. For example, on > [Render][render], you can configure environment variables in your application's > settings web page. --- ### Create a configuration file if you have many variables .breadcrumbs[
Express Best Practices
>
Use environment variables for configuration
] If you use many environment variables for configuration, you may want to centralize your configuration code in a single file, for example `config.js`: ```js // File: config.js export const port = process.env.PORT ?? 3000; export const databaseUrl = process.env.DATABASE_URL ?? 'mongodb://127.0.0.1/your-app-name'; ``` This avoids repetition if you use the same variable in different places, and serves as a sort of documentation of all your configuration parameters and their default values. You can simply import this file and use its variables where needed: ```js // File: some other file import * as config from '../path/to/config.js'; server.listen(config.port); ``` --- ### Validate complex configuration variables .breadcrumbs[
Express Best Practices
>
Use environment variables for configuration
] You always get a string value (or undefined) when you retrieve an environment variable. No check is performed for you. Some of your configuration parameters may be mandatory. Some probably need to be a specific kind of value like a positive integer or an URL. If you have a centralized configuration file like suggested earlier, you can simply add some **validation** code and throw errors in case the values are not as expected: ```js // Validate that port is a positive integer. if (process.env.PORT) { const parsedPort = Number(process.env.PORT); if (!Number.isInteger(parsedPort)) { throw new Error('Environment variable $PORT must be an integer'); } else if (parsedPort < 1 || parsedPort > 65535) { throw new Error('Environment variable $PORT must be a valid port number'); } } // Validate that some environment variable is set. if (!process.env.MY_APP_FOO) { throw new Error('Environment variable $MY_APP_FOO must be set'); } ``` --- ### The `.env` file .breadcrumbs[
Express Best Practices
>
Use environment variables for configuration
] If you use many environment variables for configuration, it can be a pain to set them all when starting your application for local development. Node.js can **load them from a file** named `.env`, with the following format: ``` PORT=4000 JWT_SECRET=replace-me-with-a-long-random-value ``` The starter's `.gitignore` file **already ignores `.env`**: it may contain secrets, so it must never be committed. > You can share this `.env` file among your team members, and everyone can adapt > it to their local environment if necessary. But never commit it. --- #### Loading the `.env` file .breadcrumbs[
Express Best Practices
>
Use environment variables for configuration
>
The `.env` file
] Add the `--env-file-if-exists` option to the `dev` script in your `package.json` file: ```json "scripts": { * "dev": "node --watch --env-file-if-exists=.env bin/start.js", "start": "node bin/start.js" } ``` - The variables are loaded **before any of your code runs** - Editing `.env` **restarts** the application, like editing your code - Variables set in your shell take precedence: `PORT=5000 npm run dev` - `--env-file=.env` would fail if the file does not exist (e.g. for a new team member) The `start` script does not need it: on [Render][render], you set the variables in the dashboard. > Tutorials often use the `dotenv` package for this. The `--env-file` option > replaces it. --- ## The `debug` package .breadcrumbs[
Express Best Practices
] The [`debug` package][debug] is a popular tool for debugging in Node.js applications, which you may use instead of `console.log`. Install it with `npm install debug`. The idea is that you create a named debug logger which you can then use to log debug messages as things happen in your application: ```js import debug from 'debug'; const log = debug('app:movies'); log('Creating movie'); log('Successfully created movie'); log('Something happened'); ``` These are **debug logs**, meaning that they **are not displayed by default**. They are meant to be enabled when you want to debug the behavior of your application in more details. --- ### Enabling debug logs .breadcrumbs[
Express Best Practices
>
The `debug` package
] The `debug` package decides whether to actually display message depending on the value of the `$DEBUG` environment variable. You can enable all debug logs by setting it to `*`: ```bash $> DEBUG=* npm start ``` Keep in mind that `debug` is a popular package and is not specific to Express. Other packages in your dependency tree might be using it (e.g. Express does). To only display a subset of the logs, you can specify a prefix: ```bash $> DEBUG=app:* npm start ``` > This would display the logs from all debug loggers that have a name starting > with `app:`. You may use this to differentiate logs within your application, > e.g. `app:database`, `app:http`, `app:api`, etc. --- ### More powerful logging .breadcrumbs[
Express Best Practices
>
The `debug` package
] The `debug` package is a minimalistic logging solution. For more features, use a more advanced library such as: - [pino] - [winston] - [log4js] --- ## Use routers .breadcrumbs[
Express Best Practices
] **Do NOT** define all your routes in `app.js`; it will get **too large and hard to maintain**. Group your API routes **by feature** and create a router for each group in the `routes` directory, then `import` them in `app.js`: ```js import express from 'express'; import `peopleApiRouter` from './routes/people.js'; import `moviesApiRouter` from './routes/movies.js'; const app = express(); // Basic middlewares configuration here (e.g. express.json())... app.use('/api/people', `peopleApiRouter`); app.use('/api/movies', `moviesApiRouter`); ``` --- ## Avoid repetition with middleware .breadcrumbs[
Express Best Practices
] You often end up with **code duplication in routes**: ```js router.get('/:id', async function(req, res, next) { * const person = await Person.findById(req.params.id).exec(); * if (!person) { * return res.sendStatus(404); * } // Send user here }); router.patch('/:id', async function(req, res, next) { * const person = await Person.findById(req.params.id).exec(); * if (!person) { * return res.sendStatus(404); * } // Update and send user here }); router.delete('/:id', async function(req, res, next) { * const person = await Person.findById(req.params.id).exec(); * if (!person) { * return res.sendStatus(404); * } // Delete user here }); ``` --- ### Writing middleware functions for common tasks .breadcrumbs[
Express Best Practices
>
Avoid repetition with middleware
] You can write a **middleware function** that performs only this task and **attaches the Person document to the `req` object**: ```js async function loadPersonFromParams(req, res, next) { const { id } = req.params; if (!mongoose.isValidObjectId(id)) { return res.status(404).send({ message: \`Person ${id} not found` }); } const person = await Person.findById(id).exec(); if (!person) { return res.status(404).send({ message: \`Person ${id} not found` }); } req.person = person; next(); } ``` Without the `isValidObjectId` check, a malformed ID such as `abc` would make `findById` throw a `CastError`, and your API would respond with a `500` error. --- ### Plugging your middleware function into routes .breadcrumbs[
Express Best Practices
>
Avoid repetition with middleware
] You can plug this function into the routes that need it. Your handler functions can then simply use `req.person`, as it will have been **loaded before they are executed**: ```js router.get('/:id', `loadPersonFromParams`, function (req, res, next) { res.send(`req.person`); }); router.patch('/:id', `loadPersonFromParams`, async function (req, res, next) { `req.person`.set(req.body); const updatedPerson = await `req.person`.save(); res.send(updatedPerson); }); router.delete('/:id', `loadPersonFromParams`, async function (req, res, next) { await `req.person`.deleteOne(); res.sendStatus(204); }); ``` --- ## Error Handling .breadcrumbs[
Express Best Practices
] The Express starter application deals with error handling in a very basic manner. ```js app.use(function (`err`, req, res, next) { res.status(err.status ?? 500); res.send({ message: err.message }); }); ``` This **middleware function** is specifically designed to handle errors. We can know this because the callback takes **four arguments, the first of which being the `err` object.** When an error is passed to the `next()` function, thrown in a middleware, or rejected by an `async` middleware, it will be caught by this error-handling middleware. This works fine for Express errors, but **we also need to handle errors thrown by MongoDB.** --- ### MongoDB errors .breadcrumbs[
Express Best Practices
>
Error Handling
] Imagine the following scenario: one of your Mongoose models specifies that a `Person` must have a unique email. Someone using your API makes a `POST` request to `/people`, trying to create a new person with an email that has already been registered. If this happens, an **ugly error message and generic status code will be sent to the user**: ```http HTTP/1.1 500 Internal Server Error Content-Type: application/json; charset=utf-8 { "message": "E11000 duplicate key error collection: …" } ``` --- ### Handling specific errors .breadcrumbs[
Express Best Practices
>
Error Handling
] In order to get a **meaningful status code and prettier error message**, we could adjust the error handling middleware to **check for this specific case**: ```js app.use(function (`err`, req, res, next) { * if (err.code === 11000) { * // err.keyValue is e.g. { email: 'jdoe@example.com' } * const [field] = Object.keys(err.keyValue); * return res.status(409).send({ message: \`${field} already exists` }); * } else if (err.name === 'ValidationError') { * return res.status(422).send({ message: err.message }); * } res.status(err.status ?? 500); res.send({ message: err.message }); }); ``` `err.keyValue` tells you **which unique field** was duplicated, so the same code works for all your unique indexes. The same goes for **invalid input**: Mongoose rejects it with a `ValidationError`, which is the **client's** mistake, so respond with `422 Unprocessable Entity` instead of `500`. [debug]: https://www.npmjs.com/package/debug [express]: https://expressjs.com [render]: https://render.com/docs/configure-environment-variables#configuring-secrets-and-other-environment-information-on-render [log4js]: https://www.npmjs.com/package/log4js [pino]: https://getpino.io [node-process-env]: https://nodejs.org/docs/latest-v26.x/api/process.html#processenv [winston]: https://www.npmjs.com/package/winston