Skip to content

Commit a163c35

Browse files
author
Sid
committed
fix: handle non-JSON responses in carbon.js to prevent crash
When the WebsiteCarbon API is protected by Cloudflare and requests originate from datacenter IPs, Cloudflare may return an HTML challenge page instead of JSON. This caused JSON.parse() to throw an uncaught SyntaxError exception, crashing the entire application. This fix: - Checks if the response starts with HTML markers before parsing - Wraps JSON.parse in try-catch for additional safety - Returns a descriptive error message instead of crashing Fixes #268
1 parent 4b4bf20 commit a163c35

1 file changed

Lines changed: 11 additions & 1 deletion

File tree

api/carbon.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,17 @@ const carbonHandler = async (url) => {
2929
data += chunk;
3030
});
3131
res.on('end', () => {
32-
resolve(JSON.parse(data));
32+
// Check if response looks like HTML (e.g., Cloudflare challenge page)
33+
const trimmedData = data.trim();
34+
if (trimmedData.startsWith('<!DOCTYPE') || trimmedData.startsWith('<html') || trimmedData.startsWith('<')) {
35+
reject(new Error('WebsiteCarbon API returned HTML instead of JSON. This may be due to Cloudflare protection when running from a datacenter IP.'));
36+
return;
37+
}
38+
try {
39+
resolve(JSON.parse(data));
40+
} catch (parseError) {
41+
reject(new Error(`Failed to parse WebsiteCarbon API response as JSON: ${parseError.message}`));
42+
}
3343
});
3444
}).on('error', reject);
3545
});

0 commit comments

Comments
 (0)