Substack subscription serverless function
Created Nov 12 2020
TYPESCRIPT1import { NowRequest, NowResponse } from '@now/node';2import axios from 'axios';34/**5* This pulls the subscription URL defined as an environment variable6*/7const { SUBSCRIPTION_URL: subscriptionURL } = process.env;89/**10* Queries the substack API11* Sends the email to the substack subscribe API for the publication specified in the url option12* @param {string} url the URL of the publication13* @param {string} email the email that needs to be added as a subscriber to the newsletter14*/15export const subscribe = async (url: string, email: string) => {16try {17const res = await axios.post(`${url}/api/v1/free`, {18first_url: `${url}/subscribe`,19first_referrer: '',20current_url: `${url}/subscribe`,21current_referrer: '',22referral_code: '',23source: 'subscribe_page',24email,25});26console.log(`${res.status} subscribed ${email} to ${subscriptionURL}`);27} catch (error) {28throw new Error(error);29}30};3132/**33* The handler of serverless function34* @param {NowRequest} req35* @param {NowResponse} res36*/37const handler = async (38req: NowRequest,39res: NowResponse40): Promise<NowResponse> => {41const { email } = req.body;4243try {44await subscribe(subscriptionURL, email);45} catch (error) {46return res.status(500).json({ error });47}4849return res.status(200).json({ response: 'subscribed!' });50};5152export default handler;