Return an image from Netlify functions

01 May 2021 in TIL

Create an image from a HTML document using AWS Lambda via Netlify Functions

I've been investigating how to create auto-generated post images using Netlify functions, and it took me a while to figure out how to return an image from the function.

It turns out that you need to return it as a base64 encoded image, and set the isBase64Encoded property to true.

Here's a snippet that renders an image:

const chromium = require("chrome-aws-lambda");
const puppeteer = require("puppeteer-core");

exports.handler = async function (event, context) {
const browser = await puppeteer.launch({
args: chromium.args,
defaultViewport: { height: 630, width: 1200 },
executablePath: await chromium.executablePath,
headless: chromium.headless,
});

const page = await browser.newPage();
await page.setContent("<body>This is a <strong>Demo</strong></body>");
await page.waitForTimeout(1000);

const buffer = await page.screenshot();

return {
statusCode: 200,
headers: {
"Content-Type": "image/png",
},
body: buffer.toString("base64"),
isBase64Encoded: true,
};
};

Save the above as netlify/functions/og.js, then make sure that you run npm install --save-dev chrome-aws-lambda puppeteer-core to add the dependencies to package.json. Next, deploy your site and visit https://your-app.netlify.app/.netlify/functions/og to see an auto-generated image.