-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsupabaseClient.js
More file actions
44 lines (38 loc) · 1.77 KB
/
Copy pathsupabaseClient.js
File metadata and controls
44 lines (38 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { createClient } from "@supabase/supabase-js";
import dotenv from "dotenv";
dotenv.config();
const SUPABASE_URL = process.env.SUPABASE_URL;
const SUPABASE_ANON_KEY = process.env.SUPABASE_ANON_KEY;
const SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!SUPABASE_URL) throw new Error("SUPABASE_URL is required");
if (!SUPABASE_SERVICE_ROLE_KEY)
throw new Error("SUPABASE_SERVICE_ROLE_KEY is required");
if (!SUPABASE_ANON_KEY) throw new Error("SUPABASE_ANON_KEY is required");
// Service-role client — bypasses RLS. Use ONLY for:
// - server-side workers (scraper sweep, email worker)
// - the x-scraper-secret protected routes
// - the unsubscribe link handler (no JWT available)
// - catalog operations on the shared `products` table
export const supabaseService = createClient(
SUPABASE_URL,
SUPABASE_SERVICE_ROLE_KEY,
{ auth: { autoRefreshToken: false, persistSession: false } },
);
// Anon client — used to validate user JWTs (auth.getUser) and as a template
// for per-request user-scoped clients.
export const supabaseAnon = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
auth: { autoRefreshToken: false, persistSession: false },
});
/**
* Per-request client whose queries run as the calling user. Supabase RLS
* policies that key on `auth.uid()` will see the user's id, so this client
* can ONLY read/write rows the user is authorized for.
*/
export const createUserClient = (jwt) =>
createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
auth: { autoRefreshToken: false, persistSession: false },
global: { headers: { Authorization: `Bearer ${jwt}` } },
});
// Default export kept as the service client for backwards compatibility
// with `app.set("supabase", supabase)` and `req.app.get("supabase")`.
export default supabaseService;