I have a hook in my Next JS project, which subscribes a user to a Klaviyo list when they submit the form on the site.
The profile is being added to Klaviyo just fine, and it all works okay from the user's perspective.
However I am getting the following console error:
klaviyoSignup.js:37 Fetch Error: SyntaxError: Unexpected end of JSON input at eval (klaviyoSignup.js:34:23)
The response returned from Klaviyo says:
{
"errors": [
{
"id": "XXXXXX",
"status": 405,
"code": "method_not_allowed",
"title": "Method \"{method}\" not allowed.",
"detail": "Method \"list\" not allowed.",
"source": {
"pointer": "/data/"
}
]
}
Here is the code for the hook:
export function klaviyoSignup(emailValue) {
console.log(emailValue);
// https://developers.klaviyo.com/en/reference/subscribe_profiles
const options = {
method: 'POST',
headers: { 'revision': '2023-12-15', 'content-type': 'application/json' },
body: JSON.stringify({
data: {
type: 'subscription',
attributes: {
profile: {
data: {
type: 'profile',
attributes: {
email: emailValue
}
}
}
},
relationships: { list: { data: { type: 'list', id: 'XXXXXX' } } }
}
})
};
fetch('https://a.klaviyo.com/client/subscriptions/?company_id=XXXXXX', options)
.then(response => {
console.log('Response Status:', response.status);
console.log('Response Headers:', response.headers);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(response => console.log('Response JSON:', response))
.catch(err => console.error('Fetch Error:', err));
}
This is using code slightly modified from Klaviyo's docs (but the functionality is all the same as their example):
https://developers.klaviyo.com/en/reference/subscribe_profiles