Skip to content

Instantly share code, notes, and snippets.

@atakde
Created July 28, 2024 09:06
Show Gist options
  • Save atakde/59507c43706f65d761b7395940431e2f to your computer and use it in GitHub Desktop.
Save atakde/59507c43706f65d761b7395940431e2f to your computer and use it in GitHub Desktop.
AWS Lambda OG Image Generator
const chromium = require('/opt/scraper-deps/node_modules/@sparticuz/chromium');
const puppeteer = require('/opt/scraper-deps/node_modules/puppeteer-core');
const handler = async (event) => {
const title = event.title || event.queryStringParameters.title || null;
if (!title) {
return {
statusCode: 400,
body: JSON.stringify({
message: 'Bad request!'
})
}
}
const url = `{YOUR_HTML_ENDPOINT}?title=${title}`
let browser;
try {
browser = await puppeteer.launch({
args: [...chromium.args],
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath(),
headless: chromium.headless,
ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080 });
await page.goto(url);
const ogContainer = '.og-container';
await page.waitForSelector(ogContainer);
const element = await page.$(ogContainer);
// Capture screenshot and save it
const image = await element.screenshot();
const base64Image = image.toString('base64');
const response = {
statusCode: 200,
body: JSON.stringify({
content: base64Image
}),
};
return response;
} catch (e) {
console.log('e', e);
} finally {
browser.close();
}
};
module.exports.handler = handler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment