What are the steps to set up an authentication file to be loaded for every test run in Playwright?


Setting Up Authentication for Every Test Run in Playwright

To ensure your authentication file is loaded for every test in Playwright, you'll need to create a setup project in your Playwright configuration file (playwright.config.ts). This project will handle authentication before all tests.

Creating the Authentication Setup

First, define a test file (auth.setup.ts) in your setup project. This file will prepare the authenticated browser state for all other tests.

// auth.setup.ts
import { setup } from '@playwright/test';

setup(async ({ page }) => {
  await page.goto('https://ray.run/login');
  await page.getByLabel('Username or email address').fill('username');
  await page.getByLabel('Password').fill('password');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await page.waitForURL('https://ray.run/');

Saving the Authenticated State

After authentication, save the authenticated state as storageState using page.context().storageState({ path: authFile }). This saves the browser's storage state into a JSON file specified by authFile.

// auth.setup.ts
import { setup } from '@playwright/test';

setup(async ({ page }) => {
  // ...authentication steps...
  await page.context().storageState({ path: 'playwright/.auth/user.json' });

Using the Authenticated State in Tests

In your testing projects (e.g., "chromium"), specify 'playwright/.auth/user.json' as the value for 'storageState'. This ensures each testing project uses the authenticated state when running tests.

// playwright.config.ts
import { PlaywrightTestConfig } from '@playwright/test';

const config: PlaywrightTestConfig = {
  projects: [
      name: 'chromium',
      use: {
        storageState: 'playwright/.auth/user.json',
    // ...other projects...

export default config;

By following these steps, your authentication file will be loaded every time a test runs in Playwright.


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.