πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 94 of 100
Security
Intermediate

How do you handle secrets in Playwright tests?

The Answer

Never hardcode secrets in test files. Use environment variables, CI secret managers, or Playwright's `storageState` to handle credentials securely.

Deep Dive Explanation

Add `playwright/.auth/*.json` to `.gitignore` since storage state files contain real session tokens. In GitHub Actions, add secrets via Settings > Secrets and reference them as `${{ secrets.TEST_PASSWORD }}`. For local dev, use a `.env` file loaded with `dotenv`.

example.spec.ts
// ❌ NEVER do this
const password = 'SuperSecret123'; // Committed to git!

// βœ… Use environment variables
const password = process.env.TEST_PASSWORD;

// βœ… Access in playwright.config.ts
export default defineConfig({
  use: {
    extraHTTPHeaders: {
      'Authorization': `Bearer ${process.env.AUTH_TOKEN}`,
    },
  },
});

// βœ… In tests
test('login with secure credentials', async ({ page }) => {
  await page.getByLabel('Password').fill(process.env.TEST_PASSWORD!);
});

// .gitignore
// .env
// playwright/.auth/
// test-results/