Substack subscription serverless function

Created Nov 12 2020

TYPESCRIPT
1
import { NowRequest, NowResponse } from "@now/node";
2
import axios from "axios";
3
4
/**
5
* This pulls the subscription URL defined as an environment variable
6
*/
7
const { SUBSCRIPTION_URL: subscriptionURL } = process.env;
8
9
/**
10
* Queries the substack API
11
* Sends the email to the substack subscribe API for the publication specified in the url option
12
* @param {string} url the URL of the publication
13
* @param {string} email the email that needs to be added as a subscriber to the newsletter
14
*/
15
export const subscribe = async (url: string, email: string) => {
16
try {
17
const res = await axios.post(`${url}/api/v1/free`, {
18
first_url: `${url}/subscribe`,
19
first_referrer: "",
20
current_url: `${url}/subscribe`,
21
current_referrer: "",
22
referral_code: "",
23
source: "subscribe_page",
24
email,
25
});
26
console.log(`${res.status} subscribed ${email} to ${subscriptionURL}`);
27
} catch (error) {
28
throw new Error(error);
29
}
30
};
31
32
/**
33
* The handler of serverless function
34
* @param {NowRequest} req
35
* @param {NowResponse} res
36
*/
37
const handler = async (
38
req: NowRequest,
39
res: NowResponse
40
): Promise<NowResponse> => {
41
const { email } = req.body;
42
43
try {
44
await subscribe(subscriptionURL, email);
45
} catch (error) {
46
return res.status(500).json({ error });
47
}
48
49
return res.status(200).json({ response: "subscribed!" });
50
};
51
52
export default handler;