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/