@@ -5,6 +5,7 @@ description: "These examples demonstrate how to run basic CRUD operations on a t
55---
66
77import SupabaseDocsCards from " /snippets/supabase-docs-cards.mdx" ;
8+ import SupabaseAuthInfo from " /snippets/supabase-auth-info.mdx" ;
89
910## Add a new user to a table in a Supabase database
1011
@@ -27,22 +28,37 @@ This is a basic task which inserts a new row into a table from a Trigger.dev tas
2728``` ts trigger/supabase-database-insert.ts
2829import { createClient } from " @supabase/supabase-js" ;
2930import { task } from " @trigger.dev/sdk/v3" ;
31+ import jwt from " jsonwebtoken" ;
3032// Generate the Typescript types using the Supabase CLI: https://supabase.com/docs/guides/api/rest/generating-types
3133import { Database } from " database.types" ;
3234
33- // Create a single Supabase client for interacting with your database
34- // 'Database' supplies the type definitions to supabase-js
35- const supabase = createClient <Database >(
36- // These details can be found in your Supabase project settings under `API`
37- process .env .SUPABASE_PROJECT_URL as string , // e.g. https://abc123.supabase.co - replace 'abc123' with your project ID
38- process .env .SUPABASE_SERVICE_ROLE_KEY as string // Your service role secret key
39- );
40-
4135export const supabaseDatabaseInsert = task ({
4236 id: " add-new-user" ,
4337 run : async (payload : { userId: string }) => {
4438 const { userId } = payload ;
4539
40+ // Get JWT secret from env vars
41+ const jwtSecret = process .env .SUPABASE_JWT_SECRET ;
42+ if (! jwtSecret ) {
43+ throw new Error (" SUPABASE_JWT_SECRET is not defined in environment variables" );
44+ }
45+
46+ // Create JWT token for the user
47+ const token = jwt .sign ({ sub: userId }, jwtSecret , { expiresIn: " 1h" });
48+
49+ // Initialize Supabase client with JWT
50+ const supabase = createClient <Database >(
51+ process .env .SUPABASE_URL as string ,
52+ process .env .SUPABASE_ANON_KEY as string ,
53+ {
54+ global: {
55+ headers: {
56+ Authorization: ` Bearer ${token } ` ,
57+ },
58+ },
59+ }
60+ );
61+
4662 // Insert a new row into the user_subscriptions table with the provided userId
4763 const { error } = await supabase .from (" user_subscriptions" ).insert ({
4864 user_id: userId ,
@@ -60,12 +76,7 @@ export const supabaseDatabaseInsert = task({
6076});
6177```
6278
63- <Note >
64- This task uses your service role secret key to bypass Row Level Security. There are different ways
65- of configuring your [ RLS
66- policies] ( https://supabase.com/docs/guides/database/postgres/row-level-security ) , so always make
67- sure you have the correct permissions set up for your project.
68- </Note >
79+ <SupabaseAuthInfo />
6980
7081### Testing your task
7182
0 commit comments