Using CloudTables in a Node.js project

Author: Colin Marks 11th March 2022

This blog is a loose transcription of the Embedding - Node.js video. We hope that this written version will help our non-English speaking users follow along and also those of you who prefer written instructions!

For reference, this is the original video:

Introduction

In this blog post I'll demonstrate how quick and easy it is to embed a CloudTable into your Node.js application.

Getting started

We'll be creating a very simple Node.js login application with the Express framework. The application consists of two files.

The first, login.html, is a login page:

<html>
    <body>
        <form action="/cloudtables" autocomplete="off" method="post">
            <input type="text" name="username" placeholder="Username" required>
            <input type="password" name="password" placeholder="Password" required>
            <input type="submit" value="Login">
        </form>
    </body>
</html>

The second, cloudtables.js, is a very simple JavaScript file that is run in Node.js for the server and serves two routes:

const express = require('express');
const path = require('path');
const app = express();

app.use(express.urlencoded({
    extended: true
}));

app.get('/', function(request, response) {
    response.sendFile(path.join(__dirname + '/login.html'));
});

app.post('/cloudtables', async function(request, response) {
    let resp = "Hello, " + request.body.username + ", how are you today?";
    response.send(resp);
    response.end();
});

app.listen(4000);

To run the app,

node cloudtables.js

and in your web browser, navigate to http://localhost:4000. There's not much to see, but it'll show the basic framework we'll be modifying.

Embedding CloudTables into the project

Before we can embed the CloudTable, we first need to add the CloudTables API into your project, with either NPM or Yarn (depending on the package manager you prefer):

# NPM
npm install --save cloudtables-api

# Yarn
yarn add cloudtables-api

To embed the CloudTable, go to the Embed tab for your data set in the CloudTables application, and click on NodeJS.

The code block you'll see in the left-hand side of the page does most of the work. It imports the CloudTables API, creates an API handle, and then generates a token. The token ties that session to the web browser session - so if your network traffic was sniffed, hackers couldn't access the CloudTables or its data because that token is already tied to the original browser session.

That code will have your domain and API keys already included, so copy to that to your clipboard and paste into the post() section of our code.

The full documentation for Node.js lists all the API methods. The API offers full CRUD functionality - you can read the contents of the data set, and also update records or create new ones. For us, we just want to generate a script tag:

let script = api.dataset('{data-set-id}').scriptTag(token);

Paste that your code. The {data-set-id} needs to be replaced with the ID of your data set - this can be found in the Data Set Inspector, on the Data tab for your data set.

And finally, we'll tweak our code to say if the user is admin, then the table is writable, otherwise it will be displayed read-only. We can do that by checking the user name and assigning API keys accordingly. These keys can be found on the Security link on the sidebar, or by changing the key on the embed page.

This gives the final post code of:

app.post("/cloudtables", async function (request, response) {
  let api = new CloudTablesApi(
    "{sub-domain}",
    request.body.username === "admin"
      ? "{read-write-key}"
      : "{read-only-key}",
    {
      clientName: request.body.username,
    }
  );

  let token = await api.token();
  let script = api
    .dataset("{data-set-id}")
    .scriptTag(token);

  response.send(script);
  response.end();
});

Note, in your code, the API keys, sub-domain, and data set IDs will be inserted into code above where we have strings in braces ({}), as yours will be specific to your environment.

That's the code complete, now you just need to restart the node server, login to that page with user admin or another user, and your table will be fully embedded.

Summary

As you've seen, it's very easy to securely embed a CloudTable in a Node.js application. I hope this has been useful - don't hesitate to get in touch if you have any questions or comments!