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:
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:
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.
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.