How can I set local storage variables prior to page loading in Puppeteer?

I’m working on a routing system that redirects users to the homepage if they lack a JWT_TOKEN. My goal is to configure this token in local storage before the page is rendered or the JavaScript executes. How can I achieve this?

Use Puppeteer's page.evaluateOnNewDocument to set local storage before any other scripts run. Here's how:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.evaluateOnNewDocument(() => {
    localStorage.setItem('JWT_TOKEN', 'your_token_here');
  });

  await page.goto('your_page_url');

  // Rest of your code...

  await browser.close();
})();

Puppeteer offers a robust way to manipulate browser sessions, and one efficient approach to set local storage prior to page loading is indeed using the page.evaluateOnNewDocument method. However, another method worth considering, particularly for scenarios involving multiple tokens or additional setup logic, involves using the page.setRequestInterception feature.

Here's an expanded example using page.evaluateOnNewDocument combined with page.setRequestInterception to manipulate requests before the page is loaded:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // Use evaluateOnNewDocument to set JWT_TOKEN
  await page.evaluateOnNewDocument(() => {
    localStorage.setItem('JWT_TOKEN', 'your_token_here');
  });

  // Enable request interception
  await page.setRequestInterception(true);
  page.on('request', (req) => {
    // Handle requests here if needed
    req.continue();
  });

  await page.goto('your_page_url');

  // Further page manipulation or interaction

  await browser.close();
})();

This approach allows you to set up the local storage as soon as the browser context is created, in addition to enabling further custom request handling if necessary. Both methods optimize the page loading process by ensuring required tokens are present prior to any script execution on your site.

To efficiently set local storage variables like JWT_TOKEN before a page loads in Puppeteer, you'll want to use the page.evaluateOnNewDocument method. This approach ensures that your local storage is configured before any web scripts execute, which aligns with your need to implement a routing system for redirection based on the presence of the token.

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // Set JWT_TOKEN using evaluateOnNewDocument
  await page.evaluateOnNewDocument(() => {
    localStorage.setItem('JWT_TOKEN', 'your_token_here');
  });

  await page.goto('your_page_url');

  // Continue with your logic...

  await browser.close();
})();

This method ensures that the JWT token is available in local storage before any JavaScript execution, achieving a seamless user redirection to the homepage if necessary. By setting this up at the beginning of your Puppeteer script, you streamline the workflow, minimizing loading delays and optimizing performance.

Use page.evaluateOnNewDocument with Puppeteer to set localStorage before any script runs:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.evaluateOnNewDocument(() => {
    localStorage.setItem('JWT_TOKEN', 'your_token_here');
  });

  await page.goto('your_page_url');

  await browser.close();
})();

While the page.evaluateOnNewDocument method has been mentioned several times and is indeed an effective strategy for setting local storage prior to page load, consider another potential approach using Puppeteer's userDataDir option. This can be useful if you wish to persist the token across multiple browser sessions.

Here's how you could implement this:

const puppeteer = require('puppeteer');

(async () => {
  // Launch browser with userDataDir to persist data across sessions
  const browser = await puppeteer.launch({
    userDataDir: './user_data', // Specify a directory to store session data
  });
  const page = await browser.newPage();

  // Navigate to the URL to set up initial storage
  await page.goto('your_page_url');

  // Use evaluateOnNewDocument to set JWT_TOKEN
  await page.evaluateOnNewDocument(() => {
    localStorage.setItem('JWT_TOKEN', 'your_token_here');
  });

  // Other logic and operations

  await browser.close();
})();

Using userDataDir allows you to retain the token across browser restarts, making it ideal for scenarios where a persistent login state is desired during testing. The combination of this technique with page.evaluateOnNewDocument provides flexibility and control over both temporary and persistent session data.