Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
API route to capture and send page screenshot with Puppeteer and Express JS
const puppeteer = require('puppeteer')
app.get('/api/snapshot', async (req, res) => {
if (!req.query.url || !req.query.width || !req.query.height) {
res.status(400).send({message: 'Invalid input'})
// Create a snapshot and send it back
try {
const browser = await puppeteer.launch({ headless: true })
const page = await browser.newPage()
await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36')
await page.setViewport({ width: parseInt(req.query.width), height: parseInt(req.query.height) })
await page.goto(req.query.url, {waitUntil: 'networkidle2'})
const buffer = await page.screenshot({type: 'png'})
// Send it back
res.setHeader('content-type', 'image/png')
res.end(null, 'binary')
// Close browser and page
await page.close()
} catch (error) {
res.status(500).send({message: 'Failed to create snapshot'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment