How to configure localStorage before page initialization in Puppeteer?

Need help with Puppeteer and localStorage

I’m working on a project where we use routing logic that redirects users to the home page if they don’t have a JWT_TOKEN set. I want to figure out how to set this token in localStorage before the page loads or any JavaScript runs.

Does anyone know how to do this in Puppeteer? I’ve tried a few things but can’t seem to get it working right. It’s important that the token is set before any page scripts run, otherwise the redirect happens and I can’t access the page I need.

Here’s a basic example of what I’m trying to do:

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

// How do I set localStorage here?
// Something like: await page.evaluate(() => localStorage.setItem('JWT_TOKEN', 'my_token'));

await page.goto('https://example.com');
// Page loads, but redirects because JWT_TOKEN isn't set in time

await browser.close();

Any help or suggestions would be greatly appreciated! Thanks in advance.

I’ve encountered this problem before and found a reliable solution that avoids using lists. The trick is to use Puppeteer’s setRequestInterception together with page.evaluateOnNewDocument so that your localStorage item is set before any page scripts execute. I enabled request interception on the page and immediately injected a script to set the JWT token in localStorage. This method guarantees that the token is present and prevents the unwanted redirect. Here’s an example:

await page.setRequestInterception(true);
page.on('request', request => request.continue());
await page.evaluateOnNewDocument(() => {
  localStorage.setItem('JWT_TOKEN', 'my_token');
});
await page.goto('https://example.com');

hey mate, i’ve run into this before. quick fix: use page.evaluateOnNewDocument() to set localStorage before the page loads. it runs before any scripts kick in. something like this:

await page.evaluateOnNewDocument(() => {
localStorage.setItem(‘JWT_TOKEN’, ‘your_token_here’);
});
await page.goto(‘https://example.com’);

should do the trick for ya. lmk if u need anything else!

I’ve tackled this issue in a recent project. The solution lies in using Puppeteer’s page.evaluateOnNewDocument() method. This function executes in the context of the page before any of its scripts run, ensuring your localStorage is set prior to page initialization.

Here’s an effective approach:

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

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

await page.goto('https://example.com');

// Your subsequent operations here

await browser.close();

This method should prevent the redirect and allow you to access your target page without issues. Remember to replace ‘your_token_here’ with your actual JWT token.