> ## Documentation Index
> Fetch the complete documentation index at: https://e2e.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Sign in once in a setup test, reuse the saved session across tests, and pass passwords and other secrets without exposing them to the AI model.

A setup test signs in once and saves a named session. Other tests restore
that session so they start already signed in. Passwords and other secrets
are opaque handles: e2e types the real value for you and shows
`<secret:name>` everywhere else (with
[a few limits](https://e2e.com/docs/reference/security#where-redaction-stops)).

<Video>
  <video src="/images/authentication.mp4" aria-label="The config declares admin credentials, a setup test signs in and saves the admin session, and a headed run opens the customers page already signed in. 15 tests pass in 12 seconds." muted loop playsInline controls />

  One setup test signs in. Every test that names `session: 'admin'` starts signed in.
</Video>

<a id="sign-in-once-in-a-setup-test" />

## Reuse authenticated sessions

Save the session in a `test.setup` body. Restore it with the `session`
option. The runner runs the setup a test needs, even when you select only
the test:

<Tabs>
  <Tab title="tests/auth.setup.e2e.ts">

```ts

test.setup('authenticate as admin', { sessions: ['admin'] }, async ({ app, screen, session, browser }) => {
  const admin = credentials.user('admin');

  await app.open('/login');
  await screen.getByLabel('Username').fill(admin.username);
  await screen.getByLabel('Password').fill(admin.password);
  await screen.getByRole('button', 'Sign in').tap();

  await expect(browser).toHaveURL('/dashboard');
  await expect(screen.getByRole('status', 'Greeting')).toContainText('admin');

  await session.save('admin');
});
```

  </Tab>
  <Tab title="tests/dashboard.e2e.ts">

```ts

test('the dashboard opens directly', { session: 'admin' }, async ({ app, screen, browser }) => {
  await app.open('/dashboard');

  await expect(browser).toHaveURL('/dashboard');
  await expect(screen.getByRole('status', 'Greeting')).toHaveText(
    'Welcome back, admin!',
  );
});
```

  </Tab>
</Tabs>

<Note>
`session.save()` doesn't check that sign-in succeeded. Assert the URL or a
signed-in element before you save.
</Note>

## Session rules

| Rule | What happens if broken |
| --- | --- |
| Define setup tests at the top level, never inside `describe` | Collection error |
| Only one setup can declare a given session name | Collection error |
| The setup body must save every name it declares | Session contract failure |
| Don't save undeclared session names | Session contract failure |
| The target engine must support saving/restoring state | Collection error before tests run (per-attempt cloud browsers can't save sessions) |

If a setup fails, any tests that depend on its session are skipped while
independent tests keep running.

In browsers, a session captures cookies, localStorage, and IndexedDB (not
server or database state). Restoring a session doesn't open a page, so still
call `app.open()` at the start of each test. Sessions last one run, are
encrypted on disk with a key held only in memory, and are deleted at
cleanup. See [Sessions](https://e2e.com/docs/reference/security#sessions).

## Credentials

Declare test accounts in your config and read passwords from the
environment:

```ts title="e2e.config.ts"

export default {
  targets: [{ engine: web(), app: { url: 'http://127.0.0.1:3000' } }],
  credentials: {
    admin: {
      username: 'admin@example.test',
      password: process.env.ADMIN_PASSWORD ?? '',
    },
  },
} satisfies E2EConfig;
```

e2e validates passwords when loading the config: if `ADMIN_PASSWORD` is
missing or shorter than 6 characters, every command fails with a config
error unless you pass an [env override](#override-a-value-per-run).

<Accordion title="Keep the value out of the environment">

Any process the runner starts can read a string from `process.env`.
`password` also accepts a function, `username` doesn't. The runner calls the
function only for an authorized fill, in the runner process, so the value
can come from a vault or be a fresh one-time code:

```ts title="e2e.config.ts"

export default {
  targets: [{ engine: web(), app: { url: 'http://127.0.0.1:3000' } }],
  credentials: {
    admin: {
      username: 'admin@example.test',
      password: () => vault.read('e2e/admin-password'),
    },
  },
} satisfies E2EConfig;
```

The value is redacted only from its first fill on. If the app can show the
value before a test types it, use a string. The same applies to a `secrets`
entry.

</Accordion>

## The password is a handle

`credentials.user(name)` returns the username as a plain string and the
password as a `Secret` named `<name>.password`. A `Secret` has no `.value`.
Pass it to a `fill` or to the `params` of an agent step:

```ts
await agent.act('Sign in', {
  params: { username: admin.username, password: admin.password },
});
```

The model sees only the secret's name and purpose. When the model fills a
password, the runner requires a password field and types the value. See the
[secret fill rules](https://e2e.com/docs/reference/security#secret-fills). The agent can't read
a secure field, so assert that sign-in succeeded instead.

Screenshots mask the password field. A value the app shows anywhere else
reaches the model. See
[screenshots after a secret fill](https://e2e.com/docs/reference/security#screenshots-after-a-secret-fill).

<Warning>
Redaction matches strings. A transformed value, such as the last four
characters of a key, can still appear. Keep secret entry in setup tests, and
assert the result of the submit. See
[where redaction stops](https://e2e.com/docs/reference/security#where-redaction-stops).
</Warning>

## Secrets that are not passwords

Use `secrets` for API keys, webhook tokens, and other values a test types:

```ts title="e2e.config.ts"

export default {
  targets: [{ engine: web(), app: { url: 'http://127.0.0.1:3000' } }],
  secrets: {
    'stripe-key': process.env.STRIPE_TEST_KEY ?? '',
    'webhook-token': process.env.WEBHOOK_TOKEN ?? '',
  },
} satisfies E2EConfig;
```

`secrets.get()` returns a handle. Use it like a password:

```ts

await screen.getByLabel('Secret key').fill(secrets.get('stripe-key'));
await agent.act('Connect Stripe with the given key', {
  params: { apiKey: secrets.get('stripe-key') },
});
```

`secrets` entries can fill any editable input, and asking for an
unconfigured secret fails the step. Because plain inputs aren't masked like
password fields, screenshots (including model screenshots) will show the
value while it's visible in the input. `credentials.admin` and
`secrets.admin` live in separate namespaces.

You can also pass `secrets.get()` to engine options that support it, like
[`basicAuth`](https://e2e.com/docs/web#protected-previews). See
[Secrets in engine options](https://e2e.com/docs/reference/security#secrets-in-engine-options).

## Override a value per run

Override any configured credential or secret for a single run with an
environment variable:

| Entry | Variable |
| --- | --- |
| `credentials.admin.username` | `E2E_USER_ADMIN_USERNAME` |
| `credentials.admin.password` | `E2E_USER_ADMIN_PASSWORD` |
| `secrets['stripe-key']` | `E2E_SECRET_STRIPE_KEY` |

Entry names are uppercased with non-alphanumeric characters turned into `_`
(two names that collide on the same env var fail config validation).

<CodeGroup>
```bash npm
E2E_USER_ADMIN_PASSWORD=... E2E_SECRET_STRIPE_KEY=sk_test_... npx e2e run
```

```bash pnpm
E2E_USER_ADMIN_PASSWORD=... E2E_SECRET_STRIPE_KEY=sk_test_... pnpm exec e2e run
```

```bash bun
E2E_USER_ADMIN_PASSWORD=... E2E_SECRET_STRIPE_KEY=sk_test_... bunx e2e run
```
</CodeGroup>

## Several signed-in users

Save one session per user. Then run the same tests with each session and
[agent](https://e2e.com/docs/agents):

<Tabs>
  <Tab title="tests/personas.setup.e2e.ts">

```ts

const PERSONAS = ['buyer', 'admin'] as const;

test.setup('sign in each persona', { sessions: [...PERSONAS] }, async ({ app, screen, session, browser }) => {
  for (const name of PERSONAS) {
    const user = credentials.user(name);
    await app.open('/login');
    await screen.getByLabel('Username').fill(user.username);
    await screen.getByLabel('Password').fill(user.password);
    await screen.getByRole('button', 'Sign in').tap();
    await expect(browser).toHaveURL('/dashboard');
    await session.save(name);
    await app.open('/logout');
  }
});
```

  </Tab>
  <Tab title="tests/checkout.e2e.ts">

```ts

for (const persona of ['buyer', 'admin'] as const) {
  describe(`checkout as ${persona}`, { agent: persona, session: persona, tags: [persona] }, () => {
    test('pays for one item', async ({ app, agent }) => {
      await app.open('/cart');
      await agent.act('pay for the item in the cart');
      await agent.assert('the order confirmation is shown');
    });
  });
}
```

  </Tab>
</Tabs>

Each name refers to an `agents` entry, a `credentials` entry, and a saved
session. When the personas don't need separate sessions,
[run one flow as several agents](https://e2e.com/docs/agents#one-flow-several-personas) instead.

## Next

<CardGroup cols={2}>
  <Card title="test reference" icon="flask" href="/reference/test">
    `test.setup`, `sessions`, and the `session` option.
  </Card>
  <Card title="Config reference" icon="sliders" href="/reference/config#credentials">
    The `credentials` and `secrets` blocks.
  </Card>
</CardGroup>
