cookiesfontsaws-lambdapuppeteerfontconfig

AWS Lambda + Puppeteer cookies - page.setCookie() not working & custom fonts not getting applied


I am using AWS Lambda + Puppeteer + Handlebars to generate PDF at runtime. I am creating the HTML on the fly and need to set cookies in order to render some images in the HTML pages before creating the PDF.

Puppeteer v4.0.0 Node v12.x

I have run into 2 issues:

  1. page.setCookie() not working
  2. I have custom fonts to be applied to the PDF - I have copied fonts and placed fonts config in the fonts folder and set FONTCONFIG_PATH env variable to /var/task/fonts (which seemed to work in PhantomJS but not in Chrome headless).

I have tried all possible ways to page.setCookie() but it doesn't seem to be working.

Code:

const page = await browser.newPage();
var pdfCookies = {
    "name": "edge-auth", // required
    "value": conf["edge-auth"], // required
    "domain": ".abc.com",
    "path": "/",
    "httponly": true,
    "secure": true
};
await page.setCookie(pdfCookies);
await page.setContent(data, {waitUntil:'networkidle0'});

I have added a console log for "await page.cookies()" - but I get a blank array [] as output.

Any help will be appreciated.


Solution

  • page.setCookie

    1. You should use page.setCookies() in the following order, otherwise puppeteer will set the required cookies on the about:blank page:
    const page = await browser.newPage();
    await page.goto(url);
    
    const pdfCookies ={
      'name': 'edge-auth',
      'value': conf["edge-auth"],
      'path': '/',
    //'domain': '.abc.com',
      'httpOnly': true,
      'secure': true
    }
    
    await page.setCookie(pdfCookies);
    
    const cookies = await page.cookies(url);
    console.log(JSON.stringify(cookies));
    

    I suggest to open any URL (or at least a Data URI like: await page.goto('data:text/html,<h1>Template</h1>');) where you can set the content later on.

    1. You also have a typo in httpOnly (it is not httponly!)
    2. Actually the 'domain':'.abc.com' pair causes the empty array. It looks to me a CORS issue.

    Fonts

    It depends on how you are using the environment variables. I suppose they are passed from the Node.js script to the Handlebars template. Make sure to use them like process.env.FONTCONFIG_PATH. You can ˙console.log()˙ it in the begenning of the script to see if it is visible to your environment or if it has the correct value.