RSS Amplifier

Nelson Lai · Sep 18, 2025

E2E Testing with Better Auth

0
Sign in to vote or save

Nelson Lai · Nelson Lai

You will need to generate a valid session token and store it as cookies. This allows your E2E tests to access authenticated routes without manual login. This method works for both credentials-based and OAuth authentication.

GitHub Repo: nelsonlaidev/e2e-testing-with-better-auth

In this guide, we'll use Playwright as our E2E testing framework, but the concepts can be applied to other frameworks like Cypress.

For simplicity, we'll use a credentials-based authentication example. However, the same principles apply to OAuth providers.

Also, we use a SQLite database for demonstration purposes. Adjust the database interactions (e.g., table names, column types) according to your setup.

To simulate an authenticated session, we'll need to generate a signed session token using BETTER_AUTH_SECRET. This token will be used in session cookies.

We want to keep our test user static to avoid creating multiple users during tests. Insert a test user, account, and session into the database if they don't already exist. We use 0 as the unique ID for all primary keys for simplicity.

Save the signed token as a cookie in a JSON file for use in testing frameworks. Don't forget to encodeURIComponent the cookie value.

Load the stored session in your E2E tests to access protected routes without logging in. The example below uses Playwright, but this can be adapted to any testing library (e.g., Cypress) that supports cookie injection.

playwright.config.ts

Read the original on nelsonlai.dev

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.