-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathsubscribe.js
More file actions
42 lines (35 loc) · 1.1 KB
/
Copy pathsubscribe.js
File metadata and controls
42 lines (35 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import fetch from 'isomorphic-unfetch';
export default async (req, res) => {
const { email } = req.body;
if (!email) {
return res.status(400).json({ error: 'Email is required' });
}
try {
const LIST_ID = process.env.MAILCHIMP_LIST_ID;
const API_KEY = process.env.MAILCHIMP_API_KEY;
const DATACENTER = API_KEY.split('-')[1];
const data = {
email_address: email,
status: 'subscribed'
};
const response = await fetch(
`https://${DATACENTER}.api.mailchimp.com/3.0/lists/${LIST_ID}/members`,
{
body: JSON.stringify(data),
headers: {
Authorization: `apikey ${API_KEY}`,
'Content-Type': 'application/json'
},
method: 'POST'
}
);
if (response.status >= 400) {
return res.status(400).json({
error: `There was an error subscribing to the newsletter. Shoot me an email at [me@leerob.io] and I'll add you to the list.`
});
}
return res.status(201).json({ error: '' });
} catch (error) {
return res.status(500).json({ error: error.message || error.toString() });
}
};