Next.js API Call to Mailchimp Contact Form - getting 500 Response

108 views Asked by At

just been working a client website and they requested that they would like to use mailchimp for their contact form but l have been stuck on the problem despite all my efforts for days l keep on getting either the 500 error response or the 400 response. Could anyone assist me as l have been stuck for days. Below is my code in the pages/api/mailer/index.ts folder

if anyone could point out what l am doing wrong that would be so appreciated as l can't spot where my error is coming from

import { NextApiRequest, NextApiResponse } from 'next';
import axios from 'axios';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    console.log('in api...')
    if (req.method === 'POST') {
        const { name, email, message } = req.body;

        // Ensure that MAILCHIMP_API_KEY is defined and not undefined
        const mailchimpApiKey = process.env.MAILCHIMP_API_KEY;
        // console.log(mailchimpApiKey)

        if (!mailchimpApiKey) {
            return res.status(500).json({ message: 'MAILCHIMP_API_KEY is not defined' });
        }

        // Construct the API endpoint URL
        const apiUrl = `${process.env.MAILCHIMP_API_SERVER}lists/${process.env.MAILCHIMP_AUDIENCE_ID}/members`;

        try {
            console.log('API Route: Submitting form data:', name, email, message);
            const response = await axios.post(
                apiUrl,
                {
                    email_address: email,
                    status: 'subscribed',
                    merge_fields: {
                        FNAME: name,
                        MMERGE3: message,
                    },
                },
                {
                    auth: {
                        username: 'apikey',
                        password: mailchimpApiKey,
                    },
                }
            );

            console.log('Mailchimp API Response:', response.data);

            if (response.status === 200) {
                res.status(200).json({ message: 'Success' });
            } else {
                res.status(500).json({ message: 'Error' });
                console.log('tough luck')
            }
        } catch (error) {
            res.status(500).json({ message: 'Error' });
        }
    } else {
        res.status(405).json({ message: 'Method Not Allowed' });
    }
}
0

There are 0 answers