
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:
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:
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: