Skip to main content
Insyrge - Zoho CRM & Business Automation Consulting
← Back to All ArticlesArtificial Intelligence, Business Automation

Playwright Authentication: Reuse Logins Safely

How to log in once, save browser state and reuse it in Playwright scripts without leaking cookies, tokens or passwords.

•Manav Sharma
Playwright Authentication: Reuse Logins Safely

Handle Playwright authentication safely: log in once, reuse saved browser state, keep state files out of Git, use separate accounts, refresh sessions.

Many useful browser automations sit behind a login: downloading reports from a supplier portal, checking order status in a vendor dashboard or testing the signed-in areas of your own application. Logging in on every run is slow, can trigger security checks and spreads credentials across more code than necessary. Playwright authentication features let a script sign in once, save the resulting browser state and reuse it on later runs. Done carelessly, though, that saved state becomes a file anyone can use to impersonate the account. This guide explains how to reuse logins safely, how to handle expiry and multiple accounts, and what to check before automating a login at all.

Check that you may automate the login

Before writing any code, confirm that automated access is allowed. Read the terms of the site or portal, and where the account belongs to a third party, get written confirmation that scripted access is acceptable. Prefer an official API or export if one exists; it will usually be more stable and easier to secure than a browser session. Our guide to Playwright web scraping covers responsible use more broadly, including rate limits and respecting site rules.

Use an account created for the automation rather than a person's own login. A dedicated account makes it clear in the site's logs which actions came from the script, lets you limit its permissions and means nobody's personal access breaks when the script's session is revoked.

How Playwright authentication works

Playwright runs each script in a browser context, an isolated session with its own cookies and storage. After a script signs in, it can save the context's state to a file and load it into new contexts later, so they start already signed in. The Playwright documentation explains that reusing authenticated state covers cookies, local storage, IndexedDB and passkey-based authentication, and notes that session storage is handled separately because it is rarely used for login information (Playwright: Authentication).

In practice the flow looks like this:

  1. A setup step opens a browser, fills in the login form and waits until a page that only signed-in users can see has loaded.
  2. The script saves the browser state to a file.
  3. Later runs create new contexts from that file and go straight to the pages they need.
  4. When the saved state stops working, the setup step runs again.

Treat state files as secrets

The saved state file holds the same cookies and tokens the site uses to recognise a signed-in user. The Playwright documentation warns that the browser state file may contain sensitive cookies and headers that could be used to impersonate you or your test account, strongly discourages checking it into private or public repositories, and recommends keeping it in a dedicated directory listed in your .gitignore file.

Practical rules:

  • Never commit state files, and add their directory to .gitignore before the first run
  • Store them only on the machine or container that runs the script, with file permissions limited to the service user
  • Delete them when the job finishes if it does not need them again soon
  • Do not attach them to bug reports, chat messages or tickets
  • Rotate the account password if a state file may have leaked, so the stolen session can be revoked

Keep credentials out of code

The setup step still needs a username and password. Keep these in environment variables or a secrets manager, not in the script. Read them at startup and fail clearly if they are missing. Make sure logs and screenshots do not capture them; for example, avoid logging form values and be careful with screenshots taken while the login form is filled in.

If the site supports it, use multi-factor authentication methods designed for automation, such as an app-specific password or a service account, rather than turning multi-factor authentication off. If a login requires a code sent to a person's phone, the process probably should not be fully automated without the site owner's agreement.

Handle expiry and failures

Saved sessions expire. Sites end sessions after a set time, after a password change or when they detect unusual activity. A robust script:

  • Checks for a signed-in marker, such as the account menu, at the start of each run
  • Falls back to the login step when the marker is missing, then saves fresh state
  • Stops and alerts after a small number of failed logins rather than retrying endlessly, which could lock the account
  • Records when state was last refreshed, so stale sessions are easy to spot

Treat repeated login failures as a signal. They often mean the site changed its login page, added a security check or revoked access.

Separate accounts and roles

When a script or test suite needs several roles, such as an administrator and a standard user, save one state file per account and load the right one for each job. Do not share one session across parallel workers that change data, because actions from one worker can affect another. The Playwright documentation describes patterns for using one account per parallel worker and for tests that need multiple signed-in roles at the same time.

Worked example: a hypothetical session plan

The table below is a hypothetical plan for a script that downloads weekly reports from two supplier portals. It illustrates the decisions to make, not a configuration for any specific site.

DecisionPortal APortal BAutomated access allowed?Yes, confirmed in writingYes, terms allow scripted exportAccount usedDedicated read-only userDedicated user with export rights onlyWhere credentials liveSecrets managerSecrets managerWhere state file livesJob container, deleted after runJob container, deleted after runSigned-in checkAccount menu visibleReports link visibleOn failed loginAlert after second failureAlert after second failureFallbackManual download by operations teamRequest CSV from supplier by email

Monitor and review access

Log each run's outcome: whether the saved state worked, whether a fresh login was needed and whether the expected pages loaded. Review the automation accounts regularly, remove access that is no longer needed and update passwords on a schedule your security policy sets. For guidance on managing credentials for machine accounts, see our post on service accounts.

Frequently Asked Questions

How do I avoid logging in on every Playwright run?

Sign in once in a setup step, save the browser state to a file and create later contexts from that file. Run the login again only when the saved state stops working.

Is it safe to commit the Playwright state file?

No. It can contain cookies and headers that let someone impersonate the account. Keep it out of version control and limit who can read it.

What should happen when a saved session expires?

The script should detect that it is no longer signed in, log in again with credentials from a secure store, save fresh state and alert if login keeps failing.

Can I share one login across parallel workers?

Only for read-only work. If workers change data, give each one its own account so their actions do not interfere.

Automate signed-in workflows safely

We review whether automated access is appropriate, design secure login handling and monitor browser automations in production. See our B2B lead mining and prospect verification service, or talk to us about Playwright authentication.

About the Author

Manav Sharma is the founder of Insyrge and a CRM solutions architect. He works across Zoho, Salesforce, HubSpot, Odoo and more, designing the CRM setups, integrations and automations that keep sales and operations teams working from the same data.

Need Help Implementing This in Your Business?

Our certified Zoho consultants and automation experts can help you design and deploy custom workflows tailored to your operations.

Book Free Consultation