Skip to main content

Reuse a logged-in state

Most test suites start by signing in. Doing that in every test is slow, and it hammers your login page. Instead, you can sign in once, save the browser's cookies and local storage to a file, and start every other test from that saved state.

This works the same way on TestingBot as it does locally. The saved state lives on the machine that runs your test script: Playwright and Puppeteer read the file there and send its contents to the remote browser over the connection to TestingBot. You do not need to upload anything to TestingBot first.

Playwright: save the state

Playwright calls this a storage state: the cookies and the local storage of every origin in a browser context, written as JSON. Sign in once and call context.storageState({ path }).

You can sign in on a TestingBot browser, as in the example below, or with a local browser: the saved file is the same either way.

const { chromium } = require('playwright')

const capabilities = {
  'tb:options': {
    key: process.env.TB_KEY,
    secret: process.env.TB_SECRET,
    name: 'Sign in and save state'
  },
  browserName: 'chrome',
  browserVersion: 'latest'
}

;(async () => {
  const browser = await chromium.connect({
    wsEndpoint: `wss://cloud.testingbot.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`
  })
  const context = await browser.newContext()
  const page = await context.newPage()

  await page.goto('https://example.com/login')
  await page.getByLabel('Email').fill(process.env.APP_USER)
  await page.getByLabel('Password').fill(process.env.APP_PASSWORD)
  await page.getByRole('button', { name: 'Sign in' }).click()
  await page.waitForURL('**/dashboard')

  // Writes cookies + local storage to a file on this machine
  await context.storageState({ path: 'state.json' })

  await browser.close()
})()

If your application keeps its login token in IndexedDB (Firebase Authentication does, for example), pass indexedDB: true as well: context.storageState({ path: 'state.json', indexedDB: true }). This option needs Playwright 1.51 or newer. IndexedDB is left out of the file by default.

Playwright: use the state on TestingBot

Pass the file to browser.newContext({ storageState }). Every page you open in that context starts signed in.

const { chromium } = require('playwright')

const capabilities = {
  'tb:options': {
    key: process.env.TB_KEY,
    secret: process.env.TB_SECRET,
    name: 'Starts signed in'
  },
  browserName: 'chrome',
  browserVersion: 'latest'
}

;(async () => {
  const browser = await chromium.connect({
    wsEndpoint: `wss://cloud.testingbot.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`
  })
  const context = await browser.newContext({ storageState: 'state.json' })
  const page = await context.newPage()

  await page.goto('https://example.com/dashboard')
  // ... the test runs as the signed-in user

  await browser.close()
})()
from playwright.sync_api import sync_playwright

with sync_playwright() as playwright:
    browser = playwright.chromium.connect('wss://cloud.testingbot.com/playwright?key=api_key&secret=api_secret&browserName=chrome&browserVersion=latest', timeout=90000)

    # Save once, after signing in:
    #   context.storage_state(path="state.json")

    context = browser.new_context(storage_state="state.json")
    page = context.new_page()
    page.goto("https://example.com/dashboard")
    # ... the test runs as the signed-in user

    browser.close()

The same storageState option works with firefox.connect() and webkit.connect(). Use the engine that matches the remote browser, as on the Playwright getting started page.

TestingBot runs the same Playwright version on the remote machine as the client that connects to it. You can override that with the playwrightVersion option, but keep it in step with your client: Playwright needs the client and the server to be on the same version.

Playwright Test setup project

With Playwright Test, sign in from a setup project and let the other projects depend on it. The setup project can run on TestingBot like any other project, by giving it the same connectOptions.

tests/auth.setup.js:

import { test as setup } from '@playwright/test'

const authFile = 'playwright/.auth/user.json'

setup('sign in', async ({ page }) => {
  await page.goto('https://example.com/login')
  await page.getByLabel('Email').fill(process.env.APP_USER)
  await page.getByLabel('Password').fill(process.env.APP_PASSWORD)
  await page.getByRole('button', { name: 'Sign in' }).click()
  await page.waitForURL('**/dashboard')

  await page.context().storageState({ path: authFile })
})

playwright.config.js, using the getConnectWsEndpoint helper from the Playwright Test page:

import { defineConfig } from '@playwright/test'
import { getConnectWsEndpoint } from './testingbot.config'

const chromeOnWindows = {
  connectOptions: {
    wsEndpoint: getConnectWsEndpoint({
      browserName: 'chrome',
      browserVersion: 'latest',
      platform: 'WIN10'
    })
  }
}

export default defineConfig({
  testDir: './tests',
  projects: [
    { name: 'setup', testMatch: /.*\.setup\.js/, use: chromeOnWindows },
    {
      name: 'chrome@latest:Windows 10',
      use: { ...chromeOnWindows, storageState: 'playwright/.auth/user.json' },
      dependencies: ['setup']
    }
  ]
})

Add playwright/.auth to your .gitignore: the file holds your session cookies.

Puppeteer: save and restore cookies

Puppeteer has no single storage-state file. Save the cookies with browser.cookies() and, if your application needs it, the origin's local storage with page.evaluate(). Restore them with browser.setCookie() before the test opens your site.

browser.cookies() and browser.setCookie() are the browser-level cookie methods of recent Puppeteer releases. On older releases, use page.cookies() and page.setCookie(...cookies) instead; recent releases mark those as deprecated.

Puppeteer's userDataDir launch option is not an alternative here: it points at a profile folder on the machine that launches the browser, and with puppeteer.connect() the browser is already running on TestingBot.

Save the state

const fs = require('fs')
const puppeteer = require('puppeteer-core')

const capabilities = {
  'tb:options': {
    key: process.env.TB_KEY,
    secret: process.env.TB_SECRET,
    name: 'Sign in and save state'
  },
  browserName: 'chrome',
  browserVersion: 'latest'
}

;(async () => {
  const browser = await puppeteer.connect({
    browserWSEndpoint: `wss://cloud.testingbot.com/puppeteer?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`
  })
  const page = await browser.newPage()

  await page.goto('https://example.com/login')
  await page.type('#email', process.env.APP_USER)
  await page.type('#password', process.env.APP_PASSWORD)
  await Promise.all([page.waitForNavigation(), page.click('button[type=submit]')])

  const state = {
    cookies: await browser.cookies(),
    origin: new URL(page.url()).origin,
    localStorage: await page.evaluate(() => Object.assign({}, window.localStorage))
  }
  fs.writeFileSync('state.json', JSON.stringify(state))

  await browser.close()
})()

Start a test from the saved state

const fs = require('fs')
const puppeteer = require('puppeteer-core')

const capabilities = {
  'tb:options': {
    key: process.env.TB_KEY,
    secret: process.env.TB_SECRET,
    name: 'Starts signed in'
  },
  browserName: 'chrome',
  browserVersion: 'latest'
}

;(async () => {
  const state = JSON.parse(fs.readFileSync('state.json', 'utf8'))
  const browser = await puppeteer.connect({
    browserWSEndpoint: `wss://cloud.testingbot.com/puppeteer?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`
  })

  await browser.setCookie(...state.cookies)

  const page = await browser.newPage()
  if (Object.keys(state.localStorage).length) {
    // localStorage belongs to an origin: open it, fill it, then continue
    await page.goto(state.origin)
    await page.evaluate((items) => {
      for (const [key, value] of Object.entries(items)) window.localStorage.setItem(key, value)
    }, state.localStorage)
  }

  await page.goto('https://example.com/dashboard')
  // ... the test runs as the signed-in user

  await browser.close()
})()

The Puppeteer examples connect to Chrome. Edge works the same way with browserName: 'edge'.

Things to keep in mind

  • The state file is a credential. Anyone with it can act as that user until the session expires. Keep it out of version control and use a dedicated test account.
  • It shows up in your test logs. TestingBot records the commands of every Playwright and Puppeteer test, so they can be reviewed in the test results. Cookies you set with context.addCookies() or browser.setCookie(), and the arguments you pass to page.evaluate(), appear there with their values. Passing the file to browser.newContext({ storageState }) is not recorded as a command.
  • Sessions expire. If tests start failing on a login page, sign in again and save a new file. In CI, run the sign-in step at the start of every pipeline run.
  • Some sites tie a session to where it was created. If your application checks the IP address or the browser of a session, a state saved on your own machine may be rejected on a TestingBot browser. Sign in on TestingBot instead, as in the examples above.
  • Session storage is not included. Neither Playwright's storage state nor the Puppeteer example above saves sessionStorage.
Was this page helpful?
Last updated