Puppeteer Quick Tip: How to do Basic Authentication
Sony AK

Sony AK @sonyarianto

About: Member of Technical Staff

Location:
Jakarta
Joined:
Nov 20, 2017

Puppeteer Quick Tip: How to do Basic Authentication

Publish Date: Dec 10 '19
18 2

A friend of mine ask about how to do basic authentication on Puppeteer. Fortunately it's quite easy.

Example of website with HTTP Basic Authentication enabled.

Alt Text

Here is the example of Puppeteer to handle HTTP Basic Authentication.

const puppeteer = require('puppeteer');

(async () => {
    // set some options, set headless to false so we can see the browser in action
    let launchOptions = { headless: false, args: ['--start-maximized'] };

    // launch the browser with above options
    const browser = await puppeteer.launch(launchOptions);
    const page = await browser.newPage();

    // set viewport and user agent (just in case for nice viewing)
    await page.setViewport({width: 1366, height: 768});
    await page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36');

    // set the HTTP Basic Authentication credential
    await page.authenticate({'username':'YOUR_BASIC_AUTH_USERNAME', 'password': 'YOUR_BASIC_AUTH_PASSWORD'});

    // go to website that protected with HTTP Basic Authentication
    await page.goto('https://WEBSITE_THAT_PROTECTED_BY_HTTP_BASIC_AUTH');

    // close the browser
    // await browser.close();
})();
Enter fullscreen mode Exit fullscreen mode

Above code will run Puppeteer on headful mode and on the last part I comment the await browser.close() to see the browser in action.

The key is this code. It will set Pupeeteer to handle the basic authentication on a website.

await page.authenticate({'username':'YOUR_BASIC_AUTH_USERNAME', 'password': 'YOUR_BASIC_AUTH_PASSWORD'});
Enter fullscreen mode Exit fullscreen mode

I hope you enjoy it. Thank you.

Comments 2 total

  • Deva
    DevaApr 17, 2020

    This works awesome in windows machine. Do we need to tweak anything to support in Linux. When i m executing this same code in docker container, seeing timeout error. Can you please suggest if you have any solution?

    • Sony AK
      Sony AKApr 21, 2020

      Hi Deva, I am using Linux (Ubuntu) and so far it has no problem, I think all browser implement for basic auth. For the timeout error it might caused by something else, maybe you should debug it first.

Add comment