Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of CORS error with mailchimp API?

How to deal with CORS error with mailchimp API?

This is my code using mailchimp package:

import mailchimp from '@mailchimp/mailchimp_marketing'

 mailchimp.setConfig({
      apiKey: process.env.NEXT_PUBLIC_MAILCHIMP_API_KEY,
      server: process.env.NEXT_PUBLIC_MAILCHIMP_DC,
});
try {
   const response = await mailchimp.lists.addListMember(process.env.NEXT_PUBLIC_MAILCHIMP_LIST_ID, {
        email_address: email,
        status: "pending",
   });
catch(err){}

And this is using axios:

const url = `https://${process.env.NEXT_PUBLIC_MAILCHIMP_DC}.api.mailchimp.com/3.0/lists/${process.env.NEXT_PUBLIC_MAILCHIMP_LIST_ID}/members`;

const { data } = await axios.post(url, providedData, {
        headers: {
          Authorization: `auth ${process.env.NEXT_PUBLIC_MAILCHIMP_API_KEY}`,
        },
});

But got the same problem!

like image 699
Ali Avatar asked Oct 19 '25 02:10

Ali


1 Answers

I solved it by calling Mailchimp API from nextJS server side
All you have to do is to go to pages/api

and add a route with the following code as an example (depending on your needs):

import mailchimp from '@mailchimp/mailchimp_marketing';

async function handler(req, res) {
  const {email_address, status, merge_fields} = req.body

  mailchimp.setConfig({
    apiKey: process.env.NEXT_PUBLIC_MAILCHIMP_API_KEY,
    server: process.env.NEXT_PUBLIC_MAILCHIMP_DC,
  });

  try {
    await mailchimp.lists.addListMember(
      process.env.NEXT_PUBLIC_MAILCHIMP_LIST_ID,
      {
        email_address,
        status,
        merge_fields
      }
    );
  } catch (err) {
    return res.status(400).send({ error: true })
  }


  return res.json({ success: true });
}

And then go to your client side and fetch this API like this:

const res = await fetch('/api/signup', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email_address: email,
          status: 'subscribed',
          merge_fields: {
            FNAME: name,
          },
        }),
  });

And that's it

like image 81
Ali Avatar answered Oct 22 '25 07:10

Ali