I'm using puppeteer in Node to take a screenshot of a domain but having some inconsistent issues.
Things work just fine when I run the code locally but when I have it deployed on Heroku I will get a 503(service unavailable) 8/10 times when I test things. Not sure why it'll work those 2/10 times.
I do have the addons in Heroku and I've tried resetting them to make sure they're uploaded in the right order like some solutions have mentioned. I've also tried changing the settings within the puppeteer function, like the ones shown here and having 'headless:true"
I'm sending the image as a base64 string to then display on the frontend.
Here's my function code, api route, and front end request:
function code:
async function captureScreenshot(domain) {
try {
const browser = await puppeteer.launch({
args: [
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
],
});
const page = await browser.newPage();
await page.setViewport({ width: 1440, height: 1080 });
await page.goto(`http://${domain}`);
let domainScreenshot = await page.screenshot({
type: "jpeg",
quality: 75,
});
domainScreenshot = Buffer.from(domainScreenshot).toString("base64");
await browser.close();
return domainScreenshot;
} catch (err) {
console.log(`❌ Error: ${err.message}`);
}
}
API Route:
router.get("/screenshot", async (req, res, next) => {
try {
const { domain } = req.query;
const buffer = await captureScreenshot(domain);
res.setHeader("Content-Type", "image/png");
res.send(buffer);
} catch (error) {
next(error);
}
});
Redux Request:
export const fetchScreenshot = (domain) => async (dispatch) => {
try {
const params = {
domain,
};
const { data: imgUrl } = await axios.get("/api/domainData/screenshot", {
params,
});
if (imgUrl) {
dispatch(setImgURL(domain, imgUrl));
}
} catch (error) {
console.error(error);
}
};
Found a solution:
I added this line to the puppeteer args array:
"--single-process"
Still have errors but it's more like 1/10 times, which is much more acceptable.