tailwind-nextjs-blog/pages/api/mailchimp.ts

27 lines
790 B
TypeScript
Raw Normal View History

2022-10-17 23:37:01 +08:00
import { NextApiRequest, NextApiResponse } from 'next';
import mailchimp from '@mailchimp/mailchimp_marketing';
2022-07-17 21:40:41 +08:00
mailchimp.setConfig({
apiKey: process.env.MAILCHIMP_API_KEY,
server: process.env.MAILCHIMP_API_SERVER, // E.g. us1
2022-10-17 23:37:01 +08:00
});
2022-07-17 21:40:41 +08:00
// eslint-disable-next-line import/no-anonymous-default-export
export default async (req: NextApiRequest, res: NextApiResponse) => {
2022-10-17 23:37:01 +08:00
const { email } = req.body;
2022-07-17 21:40:41 +08:00
if (!email) {
2022-10-17 23:37:01 +08:00
return res.status(400).json({ error: 'Email is required' });
2022-07-17 21:40:41 +08:00
}
try {
await mailchimp.lists.addListMember(process.env.MAILCHIMP_AUDIENCE_ID, {
2022-07-17 21:40:41 +08:00
email_address: email,
status: 'subscribed',
2022-10-17 23:37:01 +08:00
});
return res.status(201).json({ error: '' });
2022-07-17 21:40:41 +08:00
} catch (error) {
2022-10-17 23:37:01 +08:00
return res.status(500).json({ error: error.message || error.toString() });
2022-07-17 21:40:41 +08:00
}
2022-10-17 23:37:01 +08:00
};