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

38 lines
1.0 KiB
TypeScript
Raw Normal View History

2022-10-17 23:37:01 +08:00
import { NextApiRequest, NextApiResponse } from 'next';
2022-07-17 21:40:41 +08:00
/* eslint-disable 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 {
2022-10-17 23:37:01 +08:00
const FORM_ID = process.env.CONVERTKIT_FORM_ID;
const API_KEY = process.env.CONVERTKIT_API_KEY;
const API_URL = process.env.CONVERTKIT_API_URL;
2022-07-17 21:40:41 +08:00
// Send request to ConvertKit
2022-10-17 23:37:01 +08:00
const data = { email, api_key: API_KEY };
2022-07-17 21:40:41 +08:00
const response = await fetch(`${API_URL}forms/${FORM_ID}/subscribe`, {
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
2022-10-17 23:37:01 +08:00
});
2022-07-17 21:40:41 +08:00
if (response.status >= 400) {
return res.status(400).json({
error: `There was an error subscribing to the list.`,
2022-10-17 23:37:01 +08:00
});
2022-07-17 21:40:41 +08:00
}
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
};