'how to get rid of CORS error with mailchimp API?

How to deal with CORS error with mailchimp API?
or what is the problem with this code:

This is 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!



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1