Andrew Fredette
Andrew Fredette

Reputation: 221

Next.js API Route Works on Local Dev But Not Production (MailChimp API)

I'm working on a next.js project, and when running my project locally, I'm able to insert an email into a form and successfully POST it to MailChimp via their API. In production, the same code doesn't work, but I've confirmed that production has:

The issue seems to be after the API route is called and the subsequent API call happens. I'm lost and would love your insights.

pages/api/subscribe.js

const axios = require('axios');

const LIST_ID = 'b29d6f1e61'; // MailChimp Audience
const key = `Basic ${Buffer.from(`apikey:${process.env.MAILCHIMP_API_KEY}`).toString('base64')}`;


const subscribe = ( email ) => {
axios({
    method: 'POST',
    url: `https://us18.api.mailchimp.com/3.0/lists/${LIST_ID}/members/`,
    headers: {Authorization: key},
    data: { email_address: `${email}`, status: "subscribed" } })
    .then(response => {
        console.log(response);
        return response
    }).then(data => {
        console.log('Data Rec\'d:', data);
    }).catch(error => {
        console.log('Subscribe error:', error);
        // reject('Something went wrong')
    });

};

module.exports = async (req, res) => {
    if (req.method === 'POST') {
        res.setHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        res.send(req);
        await subscribe(req.body);
        res.end()
    } else {
        res.setHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        res.end(JSON.stringify({name: 'GET received'}))
    }
};

Upvotes: 3

Views: 416

Answers (1)

Temiloluwa
Temiloluwa

Reputation: 1

I had a similar problem and all I had to do was try the url in production, say {URL}/subscribe, then ensure you get this

{ "error": "Method GET not allowed" }

if you do not get that, check your commit on git properly to see if that route is being pushed to git and it is not being ignored. If the file is being ignored, just add it properly and redeploy.

Upvotes: 0

Related Questions