When you develop and run code on your machine, you run code in its development
environment.
Most companies will have a testing
environment similar to production; it has the same versions of software and runs on similar, albeit weaker, hardware. They do this to mitigate the risks when moving the to production
servers that clients use.
Ideally, all environments run on the same stack, platforms, and versions. Still, it is common to have developers on the Windows platform with the latest version of Node.js and the production
server running on Linux with the last stable version of Node.js. For those cases, it is essential to have a testing/staging
environment that also runs the Linux and Node.js versions found on the production server. A staging environment can detect any regressions that may occur during deployment before code reaches the user.
When we deploy the API, Heroku and similar services will look for a "start" script that uses node
to run the server. We need to add that script to package.json
.
Add a "start" script that uses node
instead of nodemon
to run index.js
.
The "scripts" section of package.json
should look like so:
"scripts": {
"start": "node index.js",
"server": "nodemon index.js"
},
dotenv
as a production dependency.index.js
:// it's recommended to load configuration for .env as early as possible
require('dotenv').config(); // add this line as the first thing to run
// server code...
// we'll read the port from the server environment if it is there
// Heroku for example will have the PORT environment variable set already
const port = process.env.PORT || 9000;
// we can now use that port, use 9000 as a default if not set by either Heroku or an .env file
server.listen(port, () => {
console.log(`\n*** Server Running on http://localhost:${port} ***\n`);
});
.env
file to the root folder (next to package.json
) with the following contentPORT=9001
It is recommended to add .env
to .gitignore
to prevent it from being uploaded to GitHub.
The reason is that most systems add configuration secrets to that file that are different between environments. Some examples are database connection credentials or API keys for external services.
.env
.9001
now as specified in .env
.Extract all secrets and values that need to change between development
and production
environments.
As of November 2022 Heroku does not provide a totally free tier like they used to, so we do not expect you to use their services. We only need you to understand how to make an API deployable to Heroku or similar providers.
The versions of project dependencies used in the recording are slightly different from the ones used in the starter and solution repositories, but this should not affect the relevant code of the Guided Project.
The versions used in the repositories are more recent, and thus more similar to the versions you will install if you create a project from scratch.