Deploy a REST API calling node.js App to Heroku
Tags: node, heroku, kintone, database
Published: 2020-02-22 01:55:50

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](https://dev-to-uploads.s3.amazonaws.com/i/zsq260svhd13oj0km172.png)

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](https://developer.kintone.io/hc/en-us/articles/220582587).


## 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](https://dev-to-uploads.s3.amazonaws.com/i/1sc2njva2dk9q1h2lncd.png)

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](https://dev-to-uploads.s3.amazonaws.com/i/hpyv0be4unlpmchoeqmk.gif)

Save the form, and navigate to the App Settings tab to [generate an API token](https://developer.kintone.io/hc/en-us/articles/229868687#creatingAPITokens). 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](https://dev-to-uploads.s3.amazonaws.com/i/2f7mg9namqa85a897t64.png)

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](https://dev-to-uploads.s3.amazonaws.com/i/fb1k3vxrtq16cnqfzqs6.png)

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
```

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](https://dev-to-uploads.s3.amazonaws.com/i/3aa5kmss9usjlcy3bi8m.png)


## 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
```

```
$ npm install express --save
```

## Preparing scripts for the node.js app

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

**index.html**
```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>
```

**mywebapp.js**
```javascript
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}`));


```

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' }
    });
```

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](https://www.freecodecamp.org/news/heres-how-you-can-actually-use-node-environment-variables-8fdf98f53a0a/)

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](https://devcenter.heroku.com/articles/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")'
    }
```

## Starting the web app

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

```
$ npm test
```

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
```

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
```
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
```

Add **node_modules** to the .gitignore file.

```
$ echo "node_modules" >> .gitignore
```

Check to see if **node_modules** was written into the file.

```
$ cat .gitignore
```

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'
```

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
```

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
```

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](https://devcenter.heroku.com/articles/deploying-nodejs#specifying-a-start-script):

*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"
  }
```

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

```
$ git add .
$ git commit -m 'my comment'
```
And then push it again to Heroku

```
$ git push heroku master
```

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:

- [Deploying a Node.js App to Heroku]
(https://stackabuse.com/deploying-a-node-js-app-to-heroku/)
- [Kintone Developer Program](https://developer.kintone.io/hc/en-us)