Open karlhorky opened 1 month ago
I think this may be actually 2 bugs though:
fetch-jsonp
calls resolve()
and removes the script on the first usage of the function
https://github.com/camsong/fetch-jsonp/blob/85d90c7e0dd7fb12f40f6eb01bb1553ed2960f58/src/fetch-jsonp.js#L40-L52,
or ||
or &&
instead, if it's supposed to be a JavaScript expression)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):
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&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: