Running Puppeteer in service workers

Is it possible to run Puppeteer in Cloudflare service worker?

I used this tutorial - https://developers.cloudflare.com/workers/archive/writing-workers/using-npm-modules/ to bundle Puppeteer. Here is the code:

index.js:

addEventListener("fetch", event => {
  event.respondWith(sendResponse(event.request));
});

const puppeteer = require("puppeteer");

async function sendResponse(request) {
  puppeteer.launch().then(async browser => {
    const page = await browser.newPage();
    await page.goto("https://google.com");
    await browser.close();
  });

  return new Response(`Hello world!`);
}

webpack.config.js

module.exports = {
  target: "webworker"
};

package.json

“scripts”: {
“build”: “webpack index.js”
},

On running npm run build, I got this error:

ERROR in ./node_modules/puppeteer/lib/WebSocketTransport.js
Module not found: Error: Can't resolve 'ws' in '/home/gijo/workspace/puppeteer-worker/node_modules/puppeteer/lib'
 @ ./node_modules/puppeteer/lib/WebSocketTransport.js 16:18-31
 @ ./node_modules/puppeteer/lib/Launcher.js
 @ ./node_modules/puppeteer/lib/Puppeteer.js
 @ ./node_modules/puppeteer/index.js
 @ ./index.js

Workers don’t support Websockets, cloudflare only send them through to the origin.

1 Like

Workers also have a 10 millisecond request time limit, puppeteer wouldn’t be able to start chrome and render the page in that time. Plus, puppeteer does need to start a sub-process for Chromium, which isn’t supported by workers.

1 Like