Luke Oliff.

Register to Chat with Typeform

·Typeform·8 min read·Luke Oliff

Also published at https://dev.to/vonagedev/register-to-chat-with-typeform-1k05

Register to Chat with Typeform

Published: November 21, 2019 | Platform: Vonage Developer Blog | Author: Luke Oliff

In this article, you’ll learn how to set up Typeform and capture data from a webhook in the Node.js framework Express.js. You’ll use Passport.js to authenticate a user, use Nexmo’s Node.js Server SDK to register a user, and generate a JWT to use with Nexmo’s JavaScript Client SDK.

You’ll be starting from a pre-built chat application built using Nexmo’s JavaScript Client SDK and Bootstrap.

This tutorial starts from the master branch and ends at the tutorial-finish branch. You can skip to the end by checking out tutorial-finish and following the README to get up and running quickly.

Prerequisites

Node & NPM

To follow this guide, you’ll need Node.js and NPM installed. This guide uses Node.js 13.1 and NPM 6.12. Check you have stable or long-term support versions of Node.js installed, at least.

If you don’t have Node.js or NPM, or you have older versions, head over to nodejs.org and install the correct version if you don’t have it.

Nexmo CLI

To set up your application, you’ll need to install the Nexmo CLI. Install it using NPM in terminal.

Now, configure the CLI using your API key and secret, found on your Nexmo account dashboard.

MongoDB

We’ll be storing information in MongoDB. If you don’t have MongoDB installed, follow the correct MongoDB Community Edition installation guide for your system.

Ngrok

Because you’ll be receiving information from a 3rd party, you’ll need to expose the application running on your local machine, but in a safe way. Ngrok is a safe way to use a single command for an instant, secure URL that allows you to access your local machine, even through a NAT or firewall.

Sign up and configure ngrok by following the instructions on their site.

Typeform

You’ll use Typeform to capture input from users, so sign-up now for a free Typeform account.

Email SMTP Provider

You’ll be sending emails. You’ll need the hostname, port, a login and a password for an SMTP provider.

You can use Google Mail to send email from an app.

Git (optional)

You can use git to clone the demo application from GitHub.

If you’re not comfortable with git, this guide also contains instructions on downloading the project as a ZIP file.

Follow this guide to install git

Starting Out

The application you’re starting with is a chat application built using Bootstrap and the Nexmo JavaScript Client SDK. It’s configurable through editing static files, but launched using Express.js, a lightweight Node.js based http server.

Basic Installation

Clone the demo application straight from GitHub.

Or, for those not comfortable with git commands, you can download the demo application as a zip file and unpack it locally.

Once cloned or unpacked, change into the new demo application directory.

Install the npm dependencies.

Installed alongside Node.js is a package called nodemon, that will automatically reload your server if you edit any files.

Start the application the standard way.

Start the application, but with nodemon instead.

Tip: If you’re running the application with nodemon for the rest of this tutorial, whenever I suggest restarting the application you won’t need to do that because nodemon does it for you. However, if you need to reauthenticate with the application, you will still need to do that, as the session information is stored in memory and not configured to use any other storage.

Whichever way you choose to run the application, once it’s running you can try it out in your favourite browser, which should be able to find it running locally: http://0.0.0.0:3000/.

As the application is unconfigured, you’ll see a very plain empty chat application that you cannot submit messages too. In the real world with error handling, you might show the user a connection error.

But, if you check the browser console now, you’ll just see a Nexmo API error for a missing token. This means the application tried to connect but didn’t provide a user token permitting access the API.

Test ngrok is configured properly, by running ngrok in a separate tab or window to npm.

You need to run this ngrok command, and npm at the same time. This means you need two terminal windows or tabs available, both at the application directory.

Tip: If you need to repeat any quests later, like submitting data from Typeform to the webhook, you can open up ngrok’s web interface at http://127.0.0.1:4040 while it’s running and Replay a request.

One thing to remember is that until you pay for ngrok, your URL will be different every time you start it. Remember this when configuring your Typeform webhook later on. If you stop ngrok, you will need to reconfigure Typeform with the new URL when you start it again.

Get Chatting

In the prerequisites, you setup your CLI using your Nexmo API key and secret. Now, you can run CLI commands to create a Nexmo application, user, conversation, join the user to the conversation and generate a JWT so your user can chat.

Nexmo Configuration

You’ll need to use some of the IDs returned once you’ve ran some of the commands. Keep a note, by copying and pasting your application, conversation, and user IDs.

Create Nexmo Application

This command creates a new Nexmo application with RTC (real-time communication) capabilities. You won’t be capturing the events in your application, so you can provide an example web address for the event URL. The private key will be output to a file path of your choice.

Create Nexmo Conversation

With an application created, you can create a conversation. The conversation will be what your users join to send messages to and fro.

Create Your User

Now, create a user. This will be the user you authenticate with. For the moment you just need a user name and display name.

Add User To Conversation

With your conversation ID and user ID, run this command to join the conversation with your user.

Generate User Token

Use this command to generate a user token in the form of a JWT, usable by the API but also by Nexmo’s JavaScript Client SDK. It will return a JWT for you to use which expires in 24 hours, or 86400 seconds.

Configure The Application

To configure your application, edit the views/layout.hbs file and find the JavaScript configuration around line 61.

<script>
  var userName = '';
  var displayName = '';
  var conversationId = '';
  var clientToken = '';
</script>

Firstly, configure the application like this, but by the end of the guide you’ll be able to authenticate with a magic link and the clientside application with get your user token from your authorized session.

Edit the config with the values you’ve generated in the commands above.

<script>
  var userName = 'luke.oliff@vonage.com';
  var displayName = 'Luke Oliff';
  var conversationId = 'CON-123...y6346';
  var clientToken = 'eyJhbG9.eyJzdWIiO.Sfl5c';
</script>

Now, you can start the application again and start chatting… with yourself… because no one else can log in.

Creating a Typeform

You can capture as much data as you like from your Typeform. But, for this guide, ensure you have a least an email field on the form.

Once you have created your Typeform, click over to the Connect tab on your Typeform edit page and click on Webhooks.

Click on Add a webhook and enter the URL as https://<your_url>.ngrok.io/webhooks/magiclink. Then click Save webhook.

Once created, you can go back and add a secret to verify requests reaching your webhook are actually coming from Typeform.

If you complete your Typeform now and submit it while your application is running, the Typeform will receive a 404 Not Found error and retry. If a webhook request fails for any reason, Typeform will retry the request to your endpoint three times using a back-off mechanism after 5, 10, and 20 minutes.

Environment Variables

From here on in, you’re going to be configuring your application with credentials that not only might differ between environments but also that you won’t want to commit along with your source code. dotenv was already a dependency of the starting project, so check out the .env file where it already contains the default port for the application.

Add a Webhook

Now, to fix your potential 404 Not Found error, add the webhook by creating a new file in the application called routes/webhook.js. In the new file, add the following code.

var express = require('express');
var router = express.Router();

/* POST webhook generates a magic link email to the provided email address */
router.post('/magiclink', (req, res, next) => {
  console.log(req.body);

  // always return a response...
  res.sendStatus(200);
});

module.exports = router;

Edit app.js and add in the webhook router.

(Note: Full tutorial content continues at the canonical URL above. This post was truncated during archiving due to length.)