Last active
February 15, 2025 01:23
-
-
Save solace/2535d75909c5e53d111a26650aaa44e4 to your computer and use it in GitHub Desktop.
Generate test Supabase tokens and cookies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {test as setup} from 'next/experimental/testmode/playwright/msw'; | |
import {uuid} from '@supabase/supabase-js/dist/main/lib/helpers'; | |
import path from 'path'; | |
import {createSupabaseCookie} from 'testing-supabase'; | |
const authFile = path.join(__dirname, '.auth/user.json'); | |
setup('authenticate', async ({page}) => { | |
await page.context().addCookies([ | |
{ | |
name: `sb-${SUPABASE_APP_ID}-auth-token`, | |
value: `base64-${createSupabaseCookie('test@email', uuid())}`, | |
domain: 'localhost', | |
path: '/', | |
expires: -1, | |
httpOnly: false, | |
secure: false, | |
sameSite: 'Lax', | |
}, | |
]); | |
await page.context().storageState({path: authFile}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Based on: https://catjam.fi/articles/supabase-gen-access-token | |
// See: https://micheleong.com/blog/testing-with-nextjs-15-and-playwright-msw-and-supabase | |
import {createSigner} from 'fast-jwt'; | |
import {encodeToBase64} from 'next/dist/build/webpack/loaders/utils'; | |
const EXPIRES_IN = 604800; | |
const signer = createSigner({ | |
// Replace with your JWT secret in Supabase if this one doesn't work. | |
// If you do, do not hard-code. Use an environment variable. | |
key: 'super-secret-jwt-token-with-at-least-32-characters-long', | |
algorithm: 'HS256', | |
}); | |
export function createSupabaseToken( | |
userEmail: string, | |
userId: string, | |
exp = Date.now() + EXPIRES_IN | |
) { | |
const payload = { | |
exp, | |
sub: userId, | |
email: userEmail, | |
role: 'authenticated', | |
}; | |
return signer(payload); | |
} | |
export function createSupabaseCookie(userEmail: string, userId: string) { | |
return encodeToBase64({ | |
access_token: createSupabaseToken(userEmail, userId), | |
refresh_token: 'refresh_token', | |
expires_in: EXPIRES_IN, | |
expires_at: Date.now() + EXPIRES_IN, | |
token_type: 'bearer', | |
user: { | |
email, | |
role: 'authenticated', | |
// user_metadata and app_metadata are optional | |
user_metadata: { | |
email, | |
}, | |
app_metadata: { | |
provider: 'email', | |
}, | |
}, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment