How do I implement a centralized login system with Playwright and TypeScript using credentials from a JSON file?


Centralized Login with Playwright and TypeScript

To implement a centralized login system using credentials from a JSON file, follow these steps:

  1. Perform authentication steps: Navigate to the login page and fill in the username and password fields with your credentials. Replace these actions with your custom actions. After filling in the fields, click on the "Sign In" button.

    await page.goto('https://ray.run/login');
    await page.fill('#username', 'your_username');
    await page.fill('#password', 'your_password');
    await page.click('#sign-in');
  2. Wait for cookies: Wait until the page receives cookies or reaches a state where all cookies are set.

  3. Store authenticated state: Call page.context().storageState({ path: 'path/to/your/file.json' }); to save your current browser context's storage state into a JSON file.

    await page.context().storageState({ path: 'path/to/your/file.json' });
  4. Use authenticated state for testing: In your configuration file, create a new setup project and declare it as a dependency for all testing projects. All testing projects should use this authenticated state as their storageState.

    import { PlaywrightTestConfig } from '@playwright/test';
    const config: PlaywrightTestConfig = {
      projects: [
          name: 'Authenticated',
          use: { storageState: 'path/to/your/file.json' },
    export default config;
  5. Specify storageState for each test: Call test.use({ storageState: 'path/to/your/file.json' }); before each test or test group that requires authentication.

    import { test } from '@playwright/test';
    test.use({ storageState: 'path/to/your/file.json' });
    test('Authenticated test', async ({ page }) => {
      // Your test code here
  6. Test multiple authenticated roles: Use multiple BrowserContexts and Pages with different storage states within the same test.

By following these steps, you can create an efficient centralized login system for testing purposes using Playwright and TypeScript.

Thank you!
Was this helpful?
Still have questions?

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

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.