I’m experiencing an issue with my Puppeteer script where I set cookies for an authenticated session and then close the browser. When I reopen it later, the cookies don’t seem to be retained. However, if I authenticate during the session, I can still access the account upon reopening the browser. I suspect it may be related to user data directory settings but I’m unsure about it. Can someone provide insights on this problem?
(async () => {
const newBrowser = await launchBrowser();
const newTab = await newBrowser.newPage();
// Load cookies to the page if available
const storedCookies = fetchStoredCookies();
if (storedCookies) {
const parsedCookies = JSON.parse(storedCookies);
const standardizedCookies = parsedCookies.map(
({ name, value, domain, path, expires, httpOnly, secure, sameSite }) => ({
name,
value,
domain,
path,
expires,
httpOnly,
secure,
sameSite,
})
);
await newTab.setCookie(...standardizedCookies);
}
// Load the target URL
await newTab.goto(TARGET_URL, {
waitUntil: 'domcontentloaded',
timeout: TIMEOUT_LIMIT,
});
await pause(5000);
await newBrowser.close();
await pause(5000);
const secondBrowser = await launchBrowser();
const secondTab = await secondBrowser.newPage();
await secondTab.goto(TARGET_URL, {
waitUntil: 'domcontentloaded',
timeout: TIMEOUT_LIMIT,
});
})();
export const launchBrowser = async ({
disableUserData = false,
isHeadless = false,
additionalArgs = []
} = {}) => {
if (activeBrowser) {
return activeBrowser;
}
const launchOptions = {
headless: isHeadless,
...(!disableUserData && {
userDataDir: './session_data/user_data',
}),
args: [
'--disable-infobars',
'--disable-notifications',
'--disable-default-browser-check',
...additionalArgs,
],
};
activeBrowser = await puppeteer.launch(launchOptions);
return activeBrowser;
};
Node Version: 21.2.0
Puppeteer Dependencies:
“puppeteer”: “^22.8.2”,
“puppeteer-extra”: “^3.3.6”,
“puppeteer-extra-plugin-session”: “^1.0.1”,
“puppeteer-extra-plugin-stealth”: “^2.11.2”,
“puppeteer-extra-plugin-user-preferences”: “^2.4.1”,
I have attempted the following solutions:
- Used both page.setCookie(…args) and network.send(“setCookie”, cookies).
- Tried manually modifying the SQLite database in userDataDir, but it did not yield any results.