-
Notifications
You must be signed in to change notification settings - Fork 156
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
Comments
I think this may be actually 2 bugs though:
|
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. |
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):
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 const response = await fetchJsonp(
- `https://xxx.us20.list-manage.com/subscribe/post-json?u=xxx&id=xxx&${new URLSearchParams({ EMAIL: email }).toString()}`,
+ `/api/mailchimp-subscriptions?u=xxx&id=xxx&${new URLSearchParams({ EMAIL: email }).toString()}`,
{
jsonpCallback: 'c',
},
); |
Thanks for the library!
With the following JSONP response (script body) from Mailchimp:
fetch-jsonp
times out, with the message (details sanitized):Looking in the DevTools console, it appears that the problem happened because of the
jsonp_1720618209454_25752
following directly after the closing parenthesis:The text was updated successfully, but these errors were encountered: