Search code examples
javascriptgoogle-cloud-functionsapify

How to use Apify on Google Cloud Functions


I'm deploying some code using Apify as Google Cloud Functions. When triggered, the Cloud Function terminates silently. What am I doing wrong?

I have some working code using Apify 0.15.1. It runs fine locally. Once deployed as a Google Cloud Function, it fails silently without any clear error. The equivalent code using Puppeteer 1.18.1 works fine.

I've reproduced the issue using more simple code below. While this example doesn't strictly require Apify, I would like to be able to use the extra functionality provided by Apify.

Code using Apify:

const Apify = require("apify");

exports.screenshotApify = async (req, res) => {
  let imageBuffer;
  Apify.main(async () => {
    const browser = await Apify.launchPuppeteer({ headless: true });
    const page = await browser.newPage();

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

    imageBuffer = await page.screenshot({ fullPage: true });

    await browser.close();
  });

  if (res) {
    res.set("Content-Type", "image/png");
    res.send(imageBuffer);
  }

  return imageBuffer;
};

Code using Puppeteer:

const puppeteer = require("puppeteer");

exports.screenshotPup = async (req, res) => {
  const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
  const page = await browser.newPage();

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

  const imageBuffer = await page.screenshot({ fullpage: true });

  await browser.close();

  if (res) {
    res.set("Content-Type", "image/png");
    res.send(imageBuffer);
  }

  return imageBuffer;
};

Once deployed as a Google Cloud Function (with --trigger-http and --memory=2048), the Puppeteer variant works fine, while the Apify variant terminates silently without result (apart from an 'ok' / HTTP 200 return value).


Solution

  • Get rid of the Apify.main() function, it schedules the call to a later time, after your function already returned the result.