How can I configure localstorage in Puppeteer before a page loads?

I have a setup where the application redirects users to the homepage if a specific token is missing from localstorage. I need to insert the necessary localstorage item before any JavaScript on the page runs so that the redirect does not trigger. I am looking for a way to modify my Puppeteer script to set this value early on. Any guidance or examples would be greatly appreciated.

I encountered a similar need in a project where the page was redirecting due to a missing token. I solved it by using page.evaluateOnNewDocument before navigating to the page. This method allowed me to inject the necessary JavaScript to set localStorage so that it was already there before any page scripts ran. I injected a snippet that simply called localStorage.setItem with the desired key and value. It took a bit of tweaking with the scrolling of scripts on the page, but it ended up working smoothly without interfering with other page functionality.