Skip to main content
Javascript

How to implement Node.js with Heroku or Docker? Part 2

In this second part we are going to investigate more about how we can implement Node.js with Heroku, so that you can make your own application and carry out your projects using these powerful tools. If you missed the first part, check this: How to implement Node.js with Heroku or Docker? Part 1

Declaring application dependencies

Heroku recognizes an application like Node.js by the existence of a file called package.json in the root directory.

For your own applications, you can create one by running the following command: npm init --yes.

The demo application you deployed already has a package.json, and it looks like this:

{"name": "node-js-getting-started", "version": "0.3.0", ... "engines": {"node": "8.11.1"}, "dependencies": {" ejs ":" ^ 2.5.6 "," express ":" ^ 4.15.2 "}, ...}

The file package.json determines both the version of Node.js that will be used to run your application on Heroku, such as the dependencies that need to be installed with your application.

When an application is deployed, Heroku reads this file and installs the appropriate Node version along with the dependencies using the command npm install.

Run this command in your local directory to install the dependencies, this goes to your system to run the application locally:

$ npm install added 132 packages in 3.368s

Once the dependencies are installed, you are ready to run your application locally.

Running the application locally

Now you must start your application locally using the following command local heroku, which was installed as part of the Heroku CLI:

$ heroku local web [OKAY] Loaded ENV .env File as KEY = VALUE Format 1:23:15 PM web.1 | Node app is running on port 5000

Like Heroku, local heroku examine the Procfile to determine what to run.

Then open the address http://localhost:5000 in your preferred web browser. You should see your application running locally.

If you want to prevent the application from running locally, in the CLI, press Ctrl + C to go out.

Make local changes

In this step, you will easily learn how to propagate a local change to your application through Heroku. As an example, you will modify the application to add an additional dependency and the code to use it.

Start by adding a dependency for cool-ascii-faces at package.json. To do this, run the following command:

$ npm install cool-ascii-faces + [email protected] added 9 packages in 2,027s

You must modify index.js so that you require this module at startup. It also adds a new path (/ cool) that uses it. Your final code should look like this:

const cool = require ('cool-ascii-faces') const express = require ('express') const path = require ('path') const PORT = process.env.PORT || 5000 express () .use (express.static (path.join (__ dirname, 'public'))) .set ('views', path.join (__ dirname,' views')) .set ('view engine', ' ejs') .get ('/', (req, res) => res.render ('pages / index')) .get ('/ cool', (req, res) => res.send (cool () )) .listen (PORT, () => console.log (`Listening on $ {PORT}`))

Now try locally:

$ npm install $ heroku local

Visiting your application at http://localhost:5000/cool, you should see pretty faces in every update: (⚆ _ ⚆). 🤗

Now deploy. Almost all deployments on Heroku follow the same pattern. First, add the modified files to the local git repository:

$ git add.

Now commit the changes to the repository:

$ git commit -m "Add cool face API"

Now deploy, just like you did before:

$ git push heroku master

Finally, check that everything works:

$ heroku open cool

You should finally see another face. 😉

Provision supplements

Add-ons are third-party cloud services that provide additional out-of-the-box services for your application, from persistence, through logging, monitoring, and much more.

By default, Heroku stores 1500 lines of records for your application. However, it makes the entire log flow available as a service, and several additional vendors have written log services that provide things like log persistence, search, and email and SMS alerts.

In this step you will provide one of these registration plugins, called Papertrail.

This is the code for the provision of the plugin for Papertrail registration:

$ heroku addons: create papertrail Adding papertrail on sharp-rain-871 ... done, v4 (free) Welcome to Papertrail. Questions and ideas are welcome ([email protected]). Happy logging! Use `heroku addons: docs papertrail` to view documentation.

To help prevent abuse, provisioning a plugin requires account verification. If your account has not been verified, you will be prompted to visit the verification site.

Maybe you are interested >>>  Building a React application from scratch

Now the plugin is implemented and configured for your application. You can make a list of plugins for your application like this:

$ heroku addons

To see this plugin in action, visit your app's Heroku URL a few times. Each visit will generate more log messages, which should now be sent to the Papertrail plugin. Visit the Papertrail console to see the log messages, this is the code:

$ heroku addons: open papertrail

Your browser will open a Papertrail web console, displaying the latest log events. The interface allows you to search and configure alerts:

Alerts
Alerts

Starting a console

To get a real idea of how power banks work, you can create another unique power bank and run the command bash, which opens a shell on that power bank.

You can then run commands there. Each powerbank has its own ephemeral file space, populated with its application and its dependencies - once the command completes (in this case, bash), the powerbank is removed.

$ heroku run bash Running 'bash' attached to terminal ... up, run.3052 ~ $ ls Procfile README.md composer.json composer.lock vendor views web ~ $ exit exit

If you get an error, Error connecting to process, you may need to configure your firewall.

Do not forget to write exit to get out of the shell and finish the power bank.

Define configuration vars

Heroku allows you to outsource configuration, storing data such as encryption keys or external resource addresses in config vars.

At run time, configuration vars are exposed as environment variables to the application. For example, modify index.js for you to enter a new path, / times, which repeats an action based on the value of the environment variable TIMES:

app.get ('/ times', (req, res) => {let result = '' const times = process.env.TIMES || 5 for (i = 0; i <times; i ++) {result + = i + ''} res.send (result)})

local heroku will automatically configure environment based on file content .env in your local directory. A file already exists in the top directory of your project .env containing the following contents:

TIMES = 2

If you run the application with local heroku, you will see that two numbers are generated each time.

To configure the config var on Heroku, run the following:

heroku config: set TIMES = 2

Then you will see the config vars that are configured using heroku config:

$ heroku config == sharp-rain-871 Config Vars PAPERTRAIL_API_TOKEN: erdKhPeeeehIcdfY7ne TIMES: 2

Deploy your modified application on Heroku and then visit it by running heroku open times.

Making the database

The plugin market has a large number of data stores, from the Redis and MongoDB providers to Postgres and MySQL. In this step, you will add a free Heroku Postgres Starter Tier development database to your application.

Add the database:

$ heroku addons: create heroku-postgresql: hobby-dev Adding heroku-postgresql: hobby-dev ... done, v3 (free)

This creates a database and sets an environment variable DATABASE_URL (you can verify this by running the command heroku config).

Use the command npm to install the module pg to your dependencies:

$ npm install pg + [email protected] added 14 packages in 2.108s
"dependencies": {"cool-ascii-faces": "^ 1.3.4", "ejs": "^ 2.5.6", "express": "^ 4.15.2", "pg": "^ 7.4. 3" },

Now edit your file index.js to use this module to connect to the database specified in your environment variable DATABASE_URL. Add this near the top:

const {Pool} = require ('pg'); const pool = new Pool ({connectionString: process.env.DATABASE_URL, ssl: true});

Now add another route, adding the following: / db just after the existing .get ('/',…) as shown in the example:

.get ('/ db', async (req, res) => {try {const client = await pool.connect () const result = await client.query ('SELECT * FROM test_table'); const results = {'results ': (result)? result.rows: null}; res.render (' pages / db ', results); client.release ();} catch (err) {console.error (err); res.send (" Error "+ err);}})

This ensures that when you access your application using the path / db, it will return all the rows in the table test_table.

Deploy this to Heroku. If you access / db, you will receive a error since there is no table in the database. Assuming you have Postgres installed locally, use the command heroku pg: psql To connect to the remote database, create a table and insert a row:

$ heroku pg: psql psql (9.5.2, server 9.6.2) SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256) Type "help" for help. => create table test_table (id integer, name text); CREATE TABLE => insert into test_table values (1, 'hello database'); INSERT 0 1 => q

Congratulations on completing this lesson! 🏅🏆🥇

error: Attention: Protected content.