I am unable to do a fetch request on my API route in netlify.
The same code works perfectly fine on Vercel. I have tried multiple ways to get around it. Still running into the issue.
This is the function that keeps failing.
async function optimizeImageFromUrl(imageUrl: string) {
const decodedUrl = decodeURIComponent(imageUrl);
const baseUrl = decodedUrl.split(‘?’)[0]; // Extract base URL (excluding query parameters)
const segments = baseUrl.split(‘/’);
const filename = segments.pop();
if (!filename) {
console.error(‘Filename could not be extracted from URL’);
return null;
}
console.warn(imageUrl);
if (/.(jpg|jpeg|png|gif|webp)$/i.test(filename)) {
try {
console.warn(‘filename’, filename);
// Use axios to get the image as an ArrayBuffer
const response = await axios.get(imageUrl, {
responseType: ‘arraybuffer’,
});
if (response.status !== 200) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const fileBuffer = Buffer.from(response.data); // Convert the ArrayBuffer to Buffer
let optimizedBuffer;
if (filename.endsWith('.webp')) {
optimizedBuffer = await sharp(fileBuffer).toBuffer();
} else {
optimizedBuffer = await sharp(fileBuffer)
.webp({ quality: 40 })
.toBuffer();
}
return {
buffer: optimizedBuffer,
filename: filename.replace(/\.(jpg|jpeg|png|gif|webp)$/i, '.webp'),
};
} catch (error) {
console.error(`Error optimizing ${filename}:`, error);
return null;
}
} else {
console.log(Ignored non-image file: ${filename}
);
return null;
}
}
…
The error is
Error: Failed to optimize image Error: HTTP error! status: 500Feb 15, 05:21:33 AM: 01HPMA3D error at P (file:///root/apps/dna-generations-app/.netlify/edge-functions/next_pages_api_content_generation_pipeline_wordpress/bundle.js:284:2903)Feb 15, 05:21:33 AM: 01HPMA3D error at eventLoopTick (ext:core/01_core.js:182:7)Feb 15, 05:21:33 AM: 01HPMA3D error at async file:///root/apps/dna-generations-app/.netlify/edge-functions/next_pages_api_content_generation_pipeline_wordpress/bundle.js:288:1631Feb 15, 05:21:33 AM: 01HPMA3D error
…
It has something to do with fetch not working properly here. I have tried both nmative fetch and AXIOS but neither seems to work. Any ideas?