André L.
André L.

Reputation: 61

How to use @mailchimp/mailchimp_marketing Package with Next.js 14 App Router API

I need to create a signup form for a Mailchimp Newsletter with my Next.js 14 Typescript Application using the new App router.

Therefore I installed @mailchimp/mailchimp_marketing packe with npm. Unfortunately I don't arrive to even ping the API.

I created the following file:
./src/app/api/newsletter/subscribe/route.ts

// route.ts

import { NextResponse } from 'next/server';
import mailchimp from '@mailchimp/mailchimp_marketing';

export async function GET() {
  mailchimp.setConfig({
    apiKey: process.env.MAILCHIMP_API_KEY,
    server: process.env.MAILCHIMP_API_SERVER,
  });

  try {
    const response = await mailchimp.ping.get();

    return NextResponse.json(response);
  } catch (error) {
    return NextResponse.json(
      {
        error: 'Failed to ping Mailchimp',
        details: JSON.stringify(error),
      },
      { status: 500 },
    );
  }
}

This always leads to the following error:

Mailchimp API error: TypeError: Cannot read properties of undefined (reading '0')
    at isInsideNodeModules (node:internal/util:521:17)
    at showFlaggedDeprecation (node:buffer:178:8)
    at new Buffer (node:buffer:266:3)
    at encoder (webpack-internal:///(rsc)/./node_modules/superagent/lib/node/index.js:498:12)
    at RequestBase._auth (webpack-internal:///(rsc)/./node_modules/superagent/lib/request-base.js:431:44)
    at Request.auth (webpack-internal:///(rsc)/./node_modules/superagent/lib/node/index.js:501:15)
    at exports.callApi (webpack-internal:///(rsc)/./node_modules/@mailchimp/mailchimp_marketing/src/ApiClient.js:396:13)
    at module.exports.getWithHttpInfo (webpack-internal:///(rsc)/./node_modules/@mailchimp/mailchimp_marketing/src/api/PingApi.js:65:27)
    at module.exports.get (webpack-internal:///(rsc)/./node_modules/@mailchimp/mailchimp_marketing/src/api/PingApi.js:77:17)
    at GET (webpack-internal:///(rsc)/./src/app/api/newsletter/subscribe/route.ts:16:107)
[...]

The API just returns {"error":"Failed to ping Mailchimp","details":"{}"}.

The error also happens if I paste the credentials as a string.
I tried it on Node v20 and Node v22.


Using JS fetch API with the same settings, everything works fine.

Working JS Fetch Example:

import { NextResponse } from 'next/server';

export async function GET() {
  const API_KEY = process.env.MAILCHIMP_API_KEY;
  const SERVER_PREFIX = process.env.MAILCHIMP_API_SERVER;
  const url = `https://${SERVER_PREFIX}.api.mailchimp.com/3.0/`;

  try {
    const response = await fetch(`${url}/ping`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `api_key ${API_KEY}`,
      },
    });

    const responseData = await response.json();
    return NextResponse.json(responseData, { status: 200 });
  } catch (error) {
    return NextResponse.json(
      {
        error: 'Failed to ping Mailchimp',
        details: JSON.stringify(error),
      },
      { status: 500 },
    );
  }
}

Upvotes: 0

Views: 325

Answers (1)

VeraciTek Inc.
VeraciTek Inc.

Reputation: 11

I'm trying to solve this exact exception that popped up on node 20.15 in a different context (pdf-parse). It was working in 20.14 and seems related to the deprecation of Buffer(). If you happen to be on 20.15 try it on 20.14 instead and it may work. No luck patching it yet though because the code that is throwing the exception isn't using new Buffer() that I can convert to Buffer API. At least not that I've found yet.

UPDATE: This is our patch for pdf-parse:

diff --git a/node_modules/pdf-parse/index.js b/node_modules/pdf-parse/index.js
index e9fc367..2a7f520 100644
--- a/node_modules/pdf-parse/index.js
+++ b/node_modules/pdf-parse/index.js
@@ -3,7 +3,7 @@ const Pdf = require('./lib/pdf-parse.js');
 
 module.exports = Pdf;
 
-let isDebugMode = !module.parent; 
+let isDebugMode = false; //20240312RAJ VeraciTek.com WUZ: let isDebugMode = !module.parent; 
 
 //process.env.AUTO_KENT_DEBUG
 
diff --git a/node_modules/pdf-parse/lib/pdf.js/v1.10.100/build/pdf.js b/node_modules/pdf-parse/lib/pdf.js/v1.10.100/build/pdf.js
index d355798..00e5c76 100644
--- a/node_modules/pdf-parse/lib/pdf.js/v1.10.100/build/pdf.js
+++ b/node_modules/pdf-parse/lib/pdf.js/v1.10.100/build/pdf.js
@@ -3939,9 +3939,15 @@ var LoopbackPort = function () {
           if (value === buffer) {
             result = value;
           } else if (transferable) {
-            result = new value.constructor(buffer, value.byteOffset, value.byteLength);
+             //20240625RAJ VeraciTek.com bug starting with node 20.15 on deprecated Buffer().
+            result = Buffer.from(buffer, value.byteOffset, value.byteLength);
+            //result = new value.constructor(buffer, value.byteOffset, value.byteLength);
           } else {
-            result = new value.constructor(value);
+            //20240625RAJ VeraciTek.com bug starting with node 20.15 on deprecated Buffer().
+            if (Buffer.isBuffer(value))
+              result = Buffer.from(value);
+            else
+              result = new value.constructor(value);
           }
           cloned.set(value, result);
           return result;
@@ -6993,7 +6999,7 @@ var SVGGraphics = function SVGGraphics() {
         if (parseInt(process.versions.node) >= 8) {
           input = literals;
         } else {
-          input = new Buffer(literals);
+          input = Buffer.from(literals);
         }
         var output = require('zlib').deflateSync(input, { level: 9 });
         return output instanceof Uint8Array ? output : new Uint8Array(output);

Upvotes: 0

Related Questions