How do I run Playwright tests in headless mode with a service account for authentication?


Sure, you can run @playwright/test in headless mode and authenticate using a service account. Here's how you do it.

First, you'll want to create an authenticated browser state and save it to a file. This can be done by creating a .auth directory in your project. Remember to add this directory to your .gitignore file to avoid committing sensitive data.

// TypeScript
import { chromium } from '@playwright/test';

async function createAuthState() {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  // Authenticate here
  const state = await context.storageState();
  // Save state to a file
  await fs.writeFile('.auth/state.json', JSON.stringify(state));
  await browser.close();


Once you've set up the authenticated browser state, you can reuse it across multiple tests. This is done by loading the state at the start of each test.

// TypeScript
import { chromium } from '@playwright/test';

async function loadAuthState() {
  const browser = await chromium.launch();
  const context = await browser.newContext({
    storageState: JSON.parse(await fs.readFile('.auth/state.json', 'utf8')),
  const page = await context.newPage();
  // Now you can use the page with the authenticated state
  await browser.close();


This approach works best when your tests don't modify server-side state and can run simultaneously with the same account. If your tests need to modify server-side state or require different accounts for parallel execution, you may need to use different authentication strategies.

Remember, running tests in headless mode with a service account can speed up test execution and improve reproducibility. Just be sure to handle server-side modifications or parallel executions that may require different accounts accordingly. Happy testing with @playwright/test!


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.