×
By the end of this chapter, you should be able to:
Now that you have built quite a few applications, it's time to share them with other people! To deploy our applications so that they're publicly visible on the internet, we will be using Heroku.
To get started, install the Heroku CLI (toolbelt) here. Make sure you also sign up for an account at heroku.com.
Let's get started with a simple application:
mkdir deploy_me && cd deploy_me touch app.js npm init -y npm install express morgan echo node_modules > .gitignore git init git add . git commit -m "initial commit"
In our app.js
// npm packages const express = require("express"); const morgan = require("morgan"); // globals const PORT = process.env.PORT || 3000; // heroku will assign a port env variable const app = express(); // app config app.use(morgan("tiny")); app.get("/", (req, res, next) => { return res.json("DEPLOYED!"); }); // catch 404 and forward to error handler app.use((req, res, next) => { const err = new Error("Not Found"); err.status = 404; return next(err); }); // error handler app.use((err, req, res, next) => { res.status(err.status || 500); return res.json({ message: err.message, /* if we're in development mode, include stack trace (full error object) otherwise, it's an empty object so the user doesn't see all of that */ error: app.get("env") === "development" ? err : {} }); }); app.listen(PORT, () => { console.log(`Server is listening on port ${PORT}`); });
Once you have signed up and installed an account make sure you are in the terminal and type in heroku login
and enter your credentials.
To create a heroku application simply type heroku create NAME_OF_YOUR_APPLICATION
(give it a good name!)
The next file we need to create is called a Procfile
. To do so we must make sure this is in the root directory and then run the following in terminal
echo web: node app.js > Procfile git add . git commit -m "adding Procfile"
Now we can deploy our application using git push heroku master
! Once we are done you can type heroku ps:scale web=1
(to start a process for your web application) and then heroku open
and you should see your application live!
For more information, see this guide on deploying Node.js applications to Heroku.
To store environment variables we can use the heroku config:set NAME_OF_VARIABLE=VALUE
and then access that variable in our node application using process.env.NAME_OF_VARIABLE
. Environment variables are essential for configuring an application for production (we will see an example of this in the next section as well). Here is what the terminal command looks like to add an environment variable:
heroku config:set DEBUG=false -a NAME_OF_APPLICATION
You can find a very simple Heroku application here.
To walkthrough the Heroku deployment process, check out this screencast:
When you're ready, move on to Adding a Postgres Database to Heroku