·
2 min read

Login at Supabase via REST API in Playwright E2E Test

Login at Supabase via REST API in Playwright E2E Test Image

I recently had to implement an end-to-end (E2E) test for a Nuxt.js application that uses Supabase as a backend and authentication provider. The test should log in a user via the Supabase REST API and then test some authenticated pages. In this article, I will show you how to implement this test with Playwright.

The simplest way is to login the user in the E2E test via UI and then test the authenticated pages. But in my case, I wanted to login the user via the REST API to speed up the test execution and/or to avoid flaky tests. I didn't find any content on the internet on how to do this, so I decided to write this article.

Setup File

We use the official docs about authentication as a starting point and define a setup file that logs in the user via the Supabase REST API and stores the session in a file:

The next step is to create a new setup project in the config and declare it as a dependency for all your testing projects that need authentication:

playwright.config.ts
export default defineConfig({ // ... projects: [ { name: 'setup', testMatch: /.*\.setup\.ts/ }, { name: 'chromium', use: { ...devices['Desktop Chrome'], }, dependencies: ['setup'], }, ], // ... })

The setup project will always run and authenticate before all the tests. The session is stored in a file that we can read in the tests for the authenticated pages and set the session in the browser's local storage which is needed by Supabase to authenticate the user:

authenticated-page.setup.ts
import fs from 'fs' import { test, expect } from '@playwright/test' import { AUTH_FREE_USER_FILE, SUPABASE_APP_ID } from './utils/constants' test('authenticated page shows logout button', async ({ page, context }) => { const sessionStorage = JSON.parse(fs.readFileSync(AUTH_FREE_USER_FILE, 'utf-8')) await context.addInitScript( (data) => { localStorage.setItem(`sb-${data.appId}-auth-token`, JSON.stringify(data.sessionStorage)) }, { sessionStorage, appId: SUPABASE_APP_ID } ) // ... test your authenticated page })

If you liked this article, follow me on X to get notified about my new blog posts and more content.

Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.

If you found this article helpful.You will love these ones as well.
Use Nitro as Mock Server Image

Use Nitro as Mock Server

Property Based Testing With Typescript Image

Property Based Testing With Typescript

How To Easily Write And Debug RxJS Marble Tests Image

How To Easily Write And Debug RxJS Marble Tests

How I Write Marble Tests For RxJS Observables In Angular Image

How I Write Marble Tests For RxJS Observables In Angular