Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple Mailchimp JSONP function calls lead to "Unexpected identifier" error #72

Open
karlhorky opened this issue Jul 10, 2024 · 3 comments

Comments

@karlhorky
Copy link

Thanks for the library!

With the following JSONP response (script body) from Mailchimp:

jsonp_1720618209454_25752({"result":"error","msg":"Too many subscribe attempts for this email address. Please try again in about 5 minutes. (#6592)"})jsonp_1720618209454_25752({"result":"error","msg":"abc@gmail.co is an invalid email address and cannot be imported."})

fetch-jsonp times out, with the message (details sanitized):

Error: JSONP request to https://xxx.us20.list-
manage.com/subscribe/post-json?u=xxx&id=xxx&EMAIL=abc%40gmail.co timed out

Looking in the DevTools console, it appears that the problem happened because of the jsonp_1720618209454_25752 following directly after the closing parenthesis:

Uncaught SyntaxError: Unexpected identifier 'jsonp_1720618209454_25752'
@karlhorky
Copy link
Author

karlhorky commented Jul 10, 2024

I think this may be actually 2 bugs though:

  1. fetch-jsonp calls resolve() and removes the script on the first usage of the function
    window[callbackFunction] = (response) => {
    resolve({
    ok: true,
    // keep consistent with fetch API
    json: () => Promise.resolve(response),
    });
    if (timeoutId) clearTimeout(timeoutId);
    removeScript(scriptId);
    clearFunction(callbackFunction);
    };
  2. A Mailchimp bug, that they are not including a semicolon between the function calls (or maybe , or || or && instead, if it's supposed to be a JavaScript expression)

@karlhorky
Copy link
Author

Looking into JSONP more, it seems like it's pretty standard to have only a single function call.

@camsong So if that's the convention, I'm happy to have this issue closed - because it would be only that Mailchimp is breaking that convention.

@karlhorky
Copy link
Author

karlhorky commented Jul 10, 2024

To work around this issue, we ended up writing our own Next.js Route Handler which passes along the request query parameters and fixes the Mailchimp response (only shows the first error):

app/api/mailchimp-subscriptions/route.ts

import { NextRequest, NextResponse } from 'next/server';

type MailchimpSubscriptionsResponseBodyGet = string;

// Fix broken Mailchimp JSONP responses (double function calls)
// https://github.com/camsong/fetch-jsonp/issues/72#issuecomment-2220956128
export async function GET(
  request: NextRequest,
): Promise<NextResponse<MailchimpSubscriptionsResponseBodyGet>> {
  const url = new URL(request.url);

  url.hostname = 'xxx.us20.list-manage.com';
  url.pathname = '/subscribe/post-json';
  url.port = '';

  const searchParams = request.nextUrl.searchParams;
  const callbackFunctionName = searchParams.get('c');

  try {
    const response = await fetch(url.toString());

    if (!response.ok) {
      return new NextResponse(
        `${callbackFunctionName}({"result":"error","msg":"Invalid response status"})`,
      );
    }

    const textResponse = await response.text();

    const firstJsonpFunctionCall = textResponse.match(
      new RegExp(`^${callbackFunctionName}\\(\\{[^}]+\\}\\)`),
    );

    if (!firstJsonpFunctionCall) {
      return new NextResponse(
        `${callbackFunctionName}({"result":"error","msg":"Invalid response format"})`,
      );
    }

    return new NextResponse(firstJsonpFunctionCall[0], {
      headers: {
        'Content-Type': 'application/javascript',
      },
    });
  } catch (error) {
    return new NextResponse(
      `${callbackFunctionName}({"result":"error","msg":"${(error as Error).message}"})`,
    );
  }
}

Then just change your call to fetchJsonp() to use the new Route Handler instead of Mailchimp directly:

const response = await fetchJsonp(
-  `https://xxx.us20.list-manage.com/subscribe/post-json?u=xxx&amp;id=xxx&${new URLSearchParams({ EMAIL: email }).toString()}`,
+  `/api/mailchimp-subscriptions?u=xxx&amp;id=xxx&${new URLSearchParams({ EMAIL: email }).toString()}`,
  {
    jsonpCallback: 'c',
  },
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant