DEV Community

Cover image for Deploy a REST API calling node.js App to Heroku
William Sayama
William Sayama

Posted on • Updated on

Deploy a REST API calling node.js App to Heroku

This tutorial shows how to deploy a node.js App to Heroku.

In this particular example, the node.js app retrieves record data from a Kintone cloud database via REST API and displays it in the page of the node.js App.

Alt Text

A Mac and a Chrome browser was used for this tutorial.

Setting up Kintone

Getting a Kintone domain

If you don't already have one, you can get a free Kintone domain by applying for a developer license.

Creating a database

Databases in Kintone are called Apps. But this is confusing considering the context, so I will notate this as App(database).

Create an App(database) from scratch
Alt Text

Drag and Drop a Text field and a Drop-down field withe the following information:

Field Type Field Name Field Code Options
Text Name name
Drop down Hobby hobby Add the following choices: Sports, Drawing, Traveling, Eating

Alt Text

Save the form, and navigate to the App Settings tab to generate an API token. Take note of this API Token, as we will be using it later in our node.js App. Also take note of the database (App) ID, which is a number that can be found inside the URL of the database (App).

Click on Activate App to deploy this database within your Kintone environment.

Adding data into the database

You will be navigated to the page of the App that displays a list of records. But since the database is empty, no records will be listed yet.

Alt Text

Click on the plus button to start adding records. Go ahead to input 5 records or so.

Click on the database(App) name to return to the record list page.

Alt Text

OK, now we have a Kintone database(app) with some data inside. From our node.js app, we will use the API token to authenticate a request to retrieve record data from this database (App).

Setting up a node.js app

We will use node v12.6.0 in this example.

Creating a package.json file

Move to a directory of your choice and start creating a package.json file with the npm init command in the terminal.

npm init
Enter fullscreen mode Exit fullscreen mode

Hit enter to answer the questions with default settings, but answer test command as node mywebapp.js.

Your package.json contents should look something like this.

Alt Text

Installing dependancies

The node.js app will need to use the Kintone JS SDK rest-api-client to make calls to Kintone, and the express module for server related code. Install these with the --save option so that the dependancies are saved into the package.json file as well.

$ npm install @kintone/rest-api-client --save
Enter fullscreen mode Exit fullscreen mode
$ npm install express --save
Enter fullscreen mode Exit fullscreen mode

Preparing scripts for the node.js app

Create the following files in the same directory as the package.json file.

index.html

<!DOCTYPE html>
<html>
<head>
    <title>My Web App</title>
</head>
<body>
    <h1>My Web App</h1>
    <form method="POST" action="/kintoneresponse">
        <input type="submit" />
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

mywebapp.js

const { KintoneRestAPIClient } = require("@kintone/rest-api-client");
const express = require('express');
const PORT = process.env.PORT || 3000;

// Create express application
const ExpressApp = express();

// Page: (root) 
// Action: display contents of /index.html
ExpressApp.get('/', function (req, res) {
    res.sendFile('/index.html', { root: __dirname });
});

// Page: (root)/kintoneresponse
// Action: Get records from Kintone database and display them
ExpressApp.post('/kintoneresponse', function (req, res) {

    const client = new KintoneRestAPIClient({
        baseUrl: 'https://xxxxx.kintone.com',
        auth: { apiToken: 'xxxxx' }
    });

    const params = {
        app: xxxxx,
        fields: ['name', 'hobby'],
        query: ''
    }

    client.record
        .getRecords(params)
        .then(resp => {
            console.dir(resp.records, { depth: null });

            // Create an HTML string to display on the page
            let htmlstring = '<ol>';
            for (i=0; i<resp.records.length; i++)
            {
                htmlstring = htmlstring 
                            + '<li>' 
                            + resp.records[i].name.value + ' likes ' + resp.records[i].hobby.value 
                            + '</li>';
            }

            htmlstring = htmlstring + "</ol>";

            // Display the html string on the page
            res.send(htmlstring);
        })
        .catch(err => {
            console.log(err);
        });
});

ExpressApp.listen(PORT, () => console.log(`Listening on ${PORT}`));


Enter fullscreen mode Exit fullscreen mode

Change the contents of the mywebapp.js file so that the URL and API token match your environment.

    const client = new KintoneRestAPIClient({
        baseUrl: 'https://xxxxx.kintone.com',
        auth: { apiToken: 'xxxxx' }
    });
Enter fullscreen mode Exit fullscreen mode

In this example, the baseURL and authentication is hardcoded so that the it's easier to understand. In reality though, you should be passing these in as environmental variables. Why? Because even if you are coding on the backend, there are still security risks when it comes to hardcoding.

Here's a great article on how to use environmental variables for node.js: freeCodeCamp|Here’s how you can actually use Node environment variables

As for using environmental variables with Heroku (which is later introduced in this article), you can use their Config Vars feature. Refer to their configuration article Configuration and Config Vars for more details.

OK, so for the next step, set the database(app) ID so it matches your database.

    const params = {
        app: xxxxx,
        fields: ['name', 'hobby'],
        query: 'hobby in ("Sports")'
    }
Enter fullscreen mode Exit fullscreen mode

Starting the web app

Run the following command which will look through package.json to run node mywebapp.js.

$ npm test
Enter fullscreen mode Exit fullscreen mode

Access http: //localhost: 3000/ in your browser to view the running web app.

Deploying and running the web app on Heroku

Now let's deploy this app to Heroku so that anybody will be able to access it.

You'll need Git to proceed, so install it if you don't have it yet. Then visit the Heroku site, sign up for an account, and follow the instructions to install the Heroku CLI.

In the directory of your package.json file, initialize git.

$ git init
Enter fullscreen mode Exit fullscreen mode

Create a .gitignore file as we want to exclude the node_modules directory from being committed (they will be generated upon deployment on Heroku).

$ touch .gitignore
Enter fullscreen mode Exit fullscreen mode

The .gitignore file is hidden, but if you are skeptical, you can use the ls command with the -a option to find it in your terminal.

$ ls -a
Enter fullscreen mode Exit fullscreen mode

Add node_modules to the .gitignore file.

$ echo "node_modules" >> .gitignore
Enter fullscreen mode Exit fullscreen mode

Check to see if node_modules was written into the file.

$ cat .gitignore
Enter fullscreen mode Exit fullscreen mode

Add an initial commit to the staging environment. Meaning that the files in this directory will be ready to be pushed onto Heroku. But it won't be pushed yet.

$ git add .
$ git commit -m 'initial commit'
Enter fullscreen mode Exit fullscreen mode

Create a Heroku App. This App will appear on the App list of your Heroku account, and also create a custom domain that you can access.

$ heroku create
Enter fullscreen mode Exit fullscreen mode

There's no content to access to yet though on that domain, as our code hasn't been pushed to Heroku. Let' do that.

$ git push heroku master
Enter fullscreen mode Exit fullscreen mode

Heroku will start creating various resources for the App.
After this is done, you will find that accessing the domain will give you an error. Earlier, we used the npm test command to run our App. A similar thing needs to be done with Heroku, which is explained in the Heroku Docs:

To determine how to start your app, Heroku first looks for a Procfile. If no Procfile exists for a Node.js app, we will attempt to start a default web process via the start script in your package.json.

Either method is find, but let's go with adding a start script in package.json. Edit this file so the the scripts section looks like the following:

"scripts": {
    "test": "node mywebapp.js",
    "start": "node mywebapp.js"
  }
Enter fullscreen mode Exit fullscreen mode

Now that we made our changes, let's commit this to the staging environment.

$ git add .
$ git commit -m 'my comment'
Enter fullscreen mode Exit fullscreen mode

And then push it again to Heroku

$ git push heroku master
Enter fullscreen mode Exit fullscreen mode

Access the custom Heroku domain, and you should see your node.js App working!

Reference

These materials were used for reference when creating this article:

Top comments (0)