Search code examples
firebasegoogle-cloud-functionstimeoutpdf-generationpuppeteer

Puppeteer PDF Creation on Firebase Functions (Google Cloud) times out


I have a function on Firebase to create a PDF file which times out every time. To investigate the issue I added debug logs with numbers. The source code of the function that I run is:

const createPDF = async (html, outputPath) => {

    console.log(1);
    let pdf;

    try {
        console.log(2);

        const browser = await puppeteer.launch();
        console.log(3);

        const page = await browser.newPage();
        console.log(4);

        await page.emulateMediaType('screen');

        console.log(5);
        await page.setContent(html, {
            waitUntil: 'networkidle0'
        });

        console.log(6);
        pdf = await page.pdf({
           // path: outputPath,
            format: 'A4',
            printBackground: true,
            margin: {
                top: "50px",
                bottom: "50px"
            }
        });

        console.log(7);
        await browser.close();

    } catch (e) {
        console.error(e);
    }

    console.log(8);
    return pdf;
};

The log says:

10:58:12.490 AM 1
10:58:12.492 AM 2
10:58:16.469 AM 3
10:58:31.236 AM Function execution took 20003 ms, finished with status: 'timeout' 

The script works, when I deploy it locally. What did I do wrong?


Solution

  • I think launch should be used with argument { args: ['--no-sandbox'] }. I have found example with this approach here.

    I created test combining provided code and helloworld cloud function, and indeed in always ended with timeout after 3. However when I used above argument it started to work fine. I tested it with 256MiB and 30 sec timeout.

    Working code:

    const puppeteer = require('puppeteer');
     
    exports.helloWorld = async (req, res) => {
      console.log(2);
    
      const browser = await puppeteer.launch({ args: ['--no-sandbox'] });
      console.log(3);
    
      const page = await browser.newPage();
      console.log(4);
      
      let message = req.query.message || req.body.message || 'Hello World!';
      res.status(200).send(message);
    };