Revue API for Newsletter Integration: React, Express & Node JavaScript

Joe Alongi
6 min readFeb 12, 2022

--

Building a newsletter is a valuable connection to your audience — email subscriptions, updates, blogs, and interesting content, shared directly to inboxes around the world.

There are many choices for deciding how to approach newsletters, gather subscribers, and communicate beyond the initial discovery. Hubspot, Mailchimp, Constant Contact, and many more marketing solutions. Exploring and managing them all is a task of its own. Building a network on top of your network has never been easier than with Revue.

Your Revue Newsletter

Signing up for a Revue account is simple, even simpler it is directly integrated with Twitter. Signing in and signing up is a breeze.

The Revue API

Once you have an account getting your API key is as simple as visiting your dashboard profile page and clicking the tab, integrations. At the bottom of the page, your API key will be annotated and highlighted for quick access.

The Revue API is quite flexible and simple to set up, with many options for GET, POST, and PATCH methods. These will allow you to gather and update information within Revue from your web or software application. For example, which many personal applications pursue, you can set up a newsletter subscription form and pass that data to Revue via API.

The one caveat that can be overlooked quite easily when running different APIs through providers and services is the requirement to proxy your Revue requests, to hide the contents of your request from the client in the browser.

You may have noticed many suggestions, questions, and even NPM packages to support this feature, in a sense, that is the purpose of this blog.

Your Subscriber API

One of the important notes required for implementing this API into your application was the requirement to Proxy the request to Revue. This information was attained as feedback from the Revue support team, which you will see many people, who are not using serverless or cloud functions trying to identify.

Setup Express Middleware

Create an Express Middleware for setting CORS, enabling methods, and enabling integrated JSON parsing.

Create the following: folder: node, filename: express.js

./node/express.js

var express = require("express");var cors = require("cors");var app = express();const revue = require("./api/revue").revue;app.use(    cors({        origin: "*",        methods: "POST",        preflightContinue: false,        optionsSuccessStatus: 204,    }),    express.json());app.post("/revue", (req, res) => {    const email = req.body.email.Email;    revue(email)        .then((response) => {            res.json({                response: response,            });        })        .catch((error) => {            res.json({                error: error,            });        });});const port = process.env.PORT;app.listen(port, () => {console.log(`Express Middleware Listening at http://localhost:${port}`);});

Setup Axios HTTP POST Request

Create an Axios HTTP POST request method that distributes the exported modules callback function to the request with the value inherited from the Express middleware route.

Create the following: folder: api, filename: revue.js

./node/api/revue.js

require("dotenv").config();const axios = require("axios");async function revue(email) {    try {        const token = process.env.REVUE_API_TOKEN;        const response = await axios.post(            "https://www.getrevue.co/api/v2/subscribers",            {                email: email,                double_opt_in: false,             },            {                headers: {                Authorization: `Token ${token}`,                "Content-Type": "application/json",             },
}
); return response; } catch (error) { return error; }}module.exports = { revue };

Depending on the request module you use to request the Revue API through Node, the request and error JSON objects may differ, which can be adjusted with Dot or Bracket notation.

A React Hooks Form

Using hooks to gather data will allow for onChange and onSubmit handling without typing together references from a Class Component and simplifying the component.

React Hook Form offers a builder that can assist here in enabling a quick form solution for building this React functional component with validation built-in.

Create the following: folder: newsletter, filename: newsletter.js

./react/src/newsletter/newsletter.js

import React from 'react';
import { useForm } from 'react-hook-form';
export default function App() { const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = data => console.log(data);
console.log(errors);

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input type="text" placeholder="Email" {...register("Email", {required: true, pattern: /^\S+@\S+$/i})} />
<input type="submit" />
</form>
);
}

Add Form Submission POST Handler

On submission of the changed form value, use the handler to dispatch a POST request to the Express endpoint which updates the Express route data fields as the email for the request to subscribe, which is added to Revue.

import React from "react";import { useForm } from "react-hook-form";import axios from "axios";export const Newsletter = () => {    const {        register,        handleSubmit,        formState: { errors },    } = useForm();    const onSubmit = (data) => {        console.log(data);        axios({            method: "post",            url: "http://localhost:4000/revue",            data: {                email: data,            },         })        .then((axios_data) => {            console.log(axios_data);        })        .catch((axios_error) => {            console.log(axios_error);        });    };    console.log(errors);    return (        <form onSubmit={handleSubmit(onSubmit)}>            <input                type="text"                placeholder="Email"                {...register("Email", { required: true, pattern: /^\S+@\S+$/i })}            />            <input type="submit" />        </form>    );};

Set Environment Variables

Environment variables keep the reserved keys, secrets, and information from being accessed directly through the DOM rendered code. Adding an .env file allows for these variables to be exposed at run-time at which they can be used to attribute dynamic values. In your React application, depending on build type these variables are instantiated at build-time.

Create the following: filename: .env

./node/.env

PORT=4000
REVUE_API_TOKEN=API_12346789

Starting Up Your Newsletter

Once there is a method in place of gathering the information from users, then making a POST request to the Node backend through Express, which makes a POST request to Revue’s API gateway, users can subscribe to your newsletter through a web application or software form.

Start both applications locally and test that the methods connect through the endpoints set at each source, React to Express and Node to Revue. The subscriber's page of your Revue dashboard should be updated once an email is processed successfully.

Thanks for Reading, Keep Emailing!

Looking for more Application Development advice? Follow along on Twitter, GitHub, and LinkedIn. Visit online for the latest updates, news, and information at heyitsjoealongi.com.

--

--