This code works in local, but when I deploy to Google App Engine I got the error "Browser var is not defined". How can I define globally the browser variable in better way? My goal is to launch puppeteer browser at startup and use the same instance to open a new webpage for each HTTP request.
const puppeteer = require('puppeteer');
const express   = require('express');
const fs        = require('fs');
var port        = process.env.PORT || 80;
const app       = express();
app.get('/request',  async (req, res, next) => {
  console.log(browser)
   //using browser var here   <---
   // UnhandledPromiseRejectionWarning: ReferenceError: browser is not defined
});
app.listen(port, () => {
  console.log('Listening on PORT: ', port)
  setup()
});
const setup = async function(){
  console.log("Initializing Puppeteer...")
  global.browser = await puppeteer.launch({
      args: [
      '--no-sandbox', 
      '--disable-setuid-sandbox', 
      '--disable-dev-shm-usage=true',
      '--disable-accelerated-2d-canvas=true',
      '--disable-gpu', 
      ]
  });
browser.on('disconnected', setup);
console.log(`Started Puppeteer with pid ${browser.process().pid}`);
}
app.yml
runtime: nodejs10
env: standard
instance_class: F4_HIGHMEM
automatic_scaling:
  max_instances: 15
  min_instances: 0
  max_pending_latency: 10ms
  max_concurrent_requests: 1
                I was able to reproduce your use case on App Engine Standard:
const puppeteer = require('puppeteer');
const express   = require('express');
const fs        = require('fs');
var port        = process.env.PORT || 80;
const app       = express();
global.browser = null;
const setup = async function(){
  console.log("Initializing Puppeteer...")
  browser = await puppeteer.launch({
      args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-dev-shm-usage=true',
      '--disable-accelerated-2d-canvas=true',
      '--disable-gpu',
      ]
  });
browser.on('disconnected', setup);
}
app.get('/', (req, res) => {
  setup();
  console.log(`Started Puppeteer with pid ${browser.process().pid}`);
  res.status(200).send('Hello, world!').end();
});
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  setup();
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});
// [END gae_node_request_example]
module.exports = app;

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With