Published on

How to run Google Puppeteer in defer.run

Authors

defer.run is platform to run background jobs. We don't have to worry about infrastructure.

You can think of this as a Heroku for background jobs. And it plays well with a serverless environment.

To run the Puppeteer script, we need to configure it a little bit though else, we'll run into an error when running the script.

npm install puppeteer @defer/client
// defer/hello-puppeteer.js
import { defer } from "@defer/client"

import puppeteer from "puppeteer";

async function helloPuppeteer() {
  try {
    const launchConfig = {
      headless: true,
      args: [
        "--no-sandbox", // Add this flag to disable the sandbox
        "--disable-setuid-sandbox",
      ]
    };

    const browser = await puppeteer.launch(launchConfig);

    const page = await browser.newPage();

    await page.goto("https://example.com");

    // your logic here ...
  } catch (error) {
    console.log(error);
    throw error;
  } finally {
    await browser.close();
  }
}

// the function must be wrapped with `defer()` and exported as default
export default defer(helloPuppeteer);

Happy running automation!