### Configure Supabase Client with Environment Variables Source: https://context7.com/advenahq/supabase-js/llms.txt This example demonstrates zero-configuration client initialization by utilizing environment variables. The Supabase client automatically picks up necessary credentials like URL and keys from `.env.local` for seamless setup. ```bash # .env.local UPV_SECRETS_SUPABASE_URL=https://your-project.supabase.co UPV_SECRETS_SUPABASE_SERVICEROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... UPV_SECRETS_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... UPV_SECRETS_SUPABASE_JWT_SECRET=your-jwt-secret ``` ```typescript import { useSupabase } from "@advenahq/supabase-js"; export default async function AutoConfigPage() { // Automatically uses environment variables - no config needed! const supabase = await useSupabase(); const { data, error } = await supabase .from("posts") .select("*") .limit(10); if (error) { console.error("Error:", error); return
Failed to load posts
; } return (

Recent Posts

{data.map((post) => (
{post.title}
))}
); } ``` -------------------------------- ### Shared Supabase Client Configuration with Supacache and Types Source: https://github.com/advenahq/supabase-js/blob/main/README.md Provides an example of a shared Supabase client configuration file that integrates Supacache for caching and utilizes database schema types generated by the Supabase CLI. This setup promotes reusability and consistent client initialization across an application. ```typescript // lib/supabase.ts import { useSupabase as _useSupabase } from "@advenahq/supabase-js"; import type { UseSupabaseOptions } from "@advenahq/supabase-js/types"; import type { Database } from "../path/to/database.types"; // https://supabase.com/docs/reference/javascript/typescript-support export const useSupabase = async ( role: "service_role" | "anon" = "service_role", // The role to use for the Supabase client, either "service_role" or "anon". Defaults to "service_role". extendConfig?: Partial | undefined, // Optional configuration to extend the default Supabase options. ) => await _useSupabase({ cache: { provider: "supacache", // Use supacache for caching supacache: { url: "https://supacache.mycloudflareworker.workers.dev", // Your supacache Worker URL serviceKey: process.env.UPV_SECRETS_SUPABASE_URL as string, // Your supacache service key }, }, role: "anon", // Use the anonymous role by default (this can be swapped out per-query by passing the "service_role" in the `role` parameter) supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, // Your project's Supabase URL auth: { keys: { secret: process.env.UPV_SECRETS_SUPABASE_SERVICEROLE_KEY, // Your project's service_role (secret) key publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY, // Your project's anon (publishable) key }, }, }); ``` -------------------------------- ### Install @advenahq/supabase-js Source: https://github.com/advenahq/supabase-js/blob/main/README.md Installs the @advenahq/supabase-js package using npm. This is the first step to integrating the Supabase client into your project. ```bash npm i @advenahq/supabase-js ``` -------------------------------- ### Configure Redis Caching with ioredis Source: https://context7.com/advenahq/supabase-js/llms.txt This example shows how to configure the Supabase client to use ioredis for caching, which is suitable for traditional server environments. It requires the `@advenahq/supabase-js` library and specifies the Redis connection URL. ```typescript import { useSupabase } from "@advenahq/supabase-js"; export default async function RedisServerPage() { const supabase = await useSupabase({ cache: { provider: "ioredis", ioredis: { url: "redis://localhost:6379", // Standard Redis connection URL }, }, role: "service_role", supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, auth: { keys: { secret: process.env.UPV_SECRETS_SUPABASE_SERVICEROLE_KEY as string, publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY as string, }, }, }); // Heavy analytics query cached in Redis const { data: analytics, error } = await supabase .from("analytics") .select("event, count, date") .gte("date", "2024-01-01") .order("date", { ascending: false }); if (error) throw error; return
Analytics events: {analytics.length}
; } ``` -------------------------------- ### Upstash Redis Provider Configuration for Caching (TypeScript) Source: https://context7.com/advenahq/supabase-js/llms.txt Illustrates how to integrate Upstash Redis for serverless-compatible caching with the Supabase client. This setup automatically handles key generation and expiry. The example shows initializing the client with Upstash connection details and setting a default TTL for cached queries. ```typescript import { useSupabase } from "@advenahq/supabase-js"; import type { Database } from "./database.types"; export default async function RedisPage() { const supabase = await useSupabase({ cache: { provider: "upstash-redis", upstash: { url: process.env.UPSTASH_REDIS_URL as string, token: process.env.UPSTASH_REDIS_TOKEN as string, behaviour: { expireSetAfter: 3600, // Default TTL: 1 hour }, }, }, role: "anon", supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, auth: { keys: { secret: process.env.UPV_SECRETS_SUPABASE_SERVICEROLE_KEY as string, publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY as string, }, }, }); // Queries automatically cached in Upstash with MD5 hash keys const { data: posts, error } = await supabase .from("blog_posts") .select("id, title, content, author_id") .eq("published", true) .order("created_at", { ascending: false }) .limit(20); if (error) { console.error("Cache MISS - fetching from database:", error); return
Error loading posts
; } return (

Recent Blog Posts

{posts.map((post) => (

{post.title}

{post.content}

))}
); } ``` -------------------------------- ### Fetching Data with Typed Responses and Custom Cache TTL Source: https://github.com/advenahq/supabase-js/blob/main/README.md Illustrates fetching data from the 'users' table using a Supabase client configured with shared settings, database types, and a custom cache TTL. This example demonstrates how to leverage generated types for the response and apply caching for performance. ```tsx // app/page.ts import { useSupabase } from "../lib/useSupabase"; import type { Tables } from "../path/to/database.types"; // https://supabase.com/docs/reference/javascript/typescript-support export default async function Page() { // Use the Supabase client exported by the shared configuration const supabase = await useSupabase(); // Fetch data from the users table const { data, error } = await supabase .from("users") .cache(86400) // Cache the response for 24 hours (86400 seconds = 24 hours) .select("*") .eq("id", 1) .limit(1) .single>(); // Use the database types to type the response // ... } ``` -------------------------------- ### Environment Variable Configuration for Supabase Client Source: https://github.com/advenahq/supabase-js/blob/main/README.md Demonstrates how the Supabase client can be automatically configured using environment variables for Supabase URL, anon key, service role key, and JWT secret. This simplifies client initialization by removing the need for explicit configuration parameters. ```bash # Retrieve these settings from your Supabase project's settings page (https://supabase.com/dashboard/project/_vnwgrcyvvigzihuvcutp_/settings/api) # The URL of the Supabase API UPV_SECRETS_SUPABASE_URL=https://.supabase.co # Your Supabase project's secret/service_role JWT (API key) UPV_SECRETS_SUPABASE_SERVICEROLE_KEY= # Your Supabase project's publishable/anon JWT (API key) UPV_SECRETS_SUPABASE_ANON_KEY= # Your Supabase project's JWT secret (for signing JWTs) UPV_SECRETS_SUPABASE_JWT_SECRET= ``` ```tsx import { useSupabase } from "@advenahq/supabase-js"; export default async function Page() { // Create a new Supabase client, relying on environment variables for configuration const supabase = await useSupabase(); // ... } ``` -------------------------------- ### Supabase Client Initialization with Service Role Source: https://github.com/advenahq/supabase-js/blob/main/README.md Shows how to initialize the Supabase client with the 'service_role' for server-side operations requiring elevated permissions. It's crucial to note that this bypasses Row Level Security (RLS) policies and should be used with caution. ```tsx import { useSupabase } from "@advenahq/supabase-js"; // ... const supabase = await useSupabase({ // your other configuration options ... role: "service_role", // Use the service role // your other configuration options ... }); // ... ``` -------------------------------- ### Browser Client Initialization with useSupabase Hook Source: https://github.com/advenahq/supabase-js/blob/main/README.md Initializes the Supabase client within a browser environment using the `useSupabase` hook. It requires importing from the browser entrypoint and expects Supabase URL and anon key to be provided, typically via environment variables. ```tsx "use client"; import { useSupabase } from '@advenahq/supabase-js/browser'; // Import the `useSupabase` hook from the browser entrypoint function MyComponent() { // Create a new Supabase browser client const supabase = useSupabase({ supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, // Your project's Supabase URL auth: { keys: { publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY as string, // Your project's anon (publishable) key }, }, }); // Use the client in the browser as you normally would supabase .channel('room1') .on('postgres_changes', { event: '*', schema: 'public', table: 'countries' }, payload => { console.log('Change received!', payload) }) .subscribe(); // ... } ``` -------------------------------- ### Browser-Side Client Initialization Source: https://context7.com/advenahq/supabase-js/llms.txt Creates a Supabase client specifically for browser/client-side operations. Automatically scrubs sensitive information like the service_role key to enhance security. ```APIDOC ## Browser-Side Client Initialization ### Description Creates a Supabase client for browser/client-side operations with automatic security scrubbing. ### Method ```typescript useSupabase({ supabaseUrl, auth}) ``` ### Parameters #### Request Body - **supabaseUrl** (string) - Required - The Supabase project URL. - **auth.keys.publishable** (string) - Required - The Supabase anon key. ### Request Example ```typescript "use client"; import { useSupabase } from "@advenahq/supabase-js/browser"; function MyComponent() { const supabase = useSupabase({ supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL as string, auth: { keys: { publishable: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY as string, }, }, }); supabase.channel("room1") .on( "postgres_changes", { event: "*", schema: "public", table: "countries" }, (payload) => { console.log("Change received!", payload); } ) .subscribe(); return
Real-time enabled
; } ``` ### Response #### Success Response (200) - **supabase** (SupabaseClient) - An initialized Supabase client instance for browser use. #### Response Example (See Request Example for context of the returned client usage) ``` -------------------------------- ### Server-Side Client Initialization Source: https://context7.com/advenahq/supabase-js/llms.txt Initializes a Supabase client for server-side operations, enabling caching, authentication, and type safety. Supports inline configuration and queries with full type safety. ```APIDOC ## Server-Side Client Initialization ### Description Initializes a Supabase client for server-side use with caching, authentication, and type safety. ### Method ```typescript useSupabase(config: SupabaseConfig) ``` ### Parameters #### Request Body - **config** (object) - Required - Configuration object for Supabase client. - **role** (string) - Optional - The role to use for the Supabase client (e.g., 'anon', 'authenticated'). - **supabaseUrl** (string) - Required - The Supabase project URL. - **auth.keys.secret** (string) - Required (for service role) - The Supabase service role key. - **auth.keys.publishable** (string) - Required - The Supabase anon key. ### Request Example ```typescript import { useSupabase } from "@advenahq/supabase-js"; import type { Database } from "./database.types"; export default async function Page() { const supabase = await useSupabase({ role: "anon", supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, auth: { keys: { secret: process.env.UPV_SECRETS_SUPABASE_SERVICEROLE_KEY as string, publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY as string, }, }, }); const { data, error } = await supabase.from("users").select("*").eq("id", 1).limit(1).single(); if (error) { console.error("Query failed:", error); return null; } return
User: {data.name}
; } ``` ### Response #### Success Response (200) - **supabase** (SupabaseClient) - An initialized Supabase client instance. #### Response Example (See Request Example for context of the returned client usage) ``` -------------------------------- ### Initialize Supabase Client Inline with useSupabase Hook (TypeScript/Next.js) Source: https://github.com/advenahq/supabase-js/blob/main/README.md Demonstrates how to initialize a Supabase client within a Next.js page component using the useSupabase hook. It configures the client inline with specified roles and authentication keys, enabling server-side data fetching. ```tsx import { useSupabase } from "@advenahq/supabase-js"; export default async function Page() { // Create a new Supabase client, configuring it inline const supabase = await useSupabase({ role: "anon", // Use the anonymous role supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, // Your project's Supabase URL auth: { keys: { secret: process.env.UPV_SECRETS_SUPABASE_SERVICEROLE_KEY as string, // Your project's service_role (secret) key publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY as string, // Your project's anon (publishable) key }, }, }); // Then, just use the client as you normally would const { data, error } = await supabase .from("users") .select("*") .eq("id", 1) .limit(1) .single(); // ... } ``` -------------------------------- ### Shared Supabase Client Configuration (TypeScript) Source: https://context7.com/advenahq/supabase-js/llms.txt Sets up a reusable `useSupabase` function for initializing the Supabase client with consistent configuration across an application. It supports different authentication roles (service_role, anon) and allows for extending default options. The function utilizes environment variables for Supabase URL, API keys, and Supacache configuration. ```typescript // lib/supabase.ts import { useSupabase as _useSupabase } from "@advenahq/supabase-js"; import type { UseSupabaseOptions } from "@advenahq/supabase-js/types"; import type { Database } from "../types/database.types"; export const useSupabase = async ( role: "service_role" | "anon" = "service_role", extendConfig?: Partial | undefined ) => await _useSupabase({ cache: { provider: "supacache", supacache: { url: process.env.SUPACACHE_URL as string, serviceKey: process.env.SUPACACHE_SERVICE_KEY as string, }, }, role: role, supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, auth: { keys: { secret: process.env.UPV_SECRETS_SUPABASE_SERVICEROLE_KEY, publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY, }, }, ...extendConfig, }); // app/page.tsx import { useSupabase } from "../lib/supabase"; export default async function Page() { // Use service role by default const adminClient = await useSupabase("service_role"); // Or use anon role with RLS const userClient = await useSupabase("anon"); const { data } = await userClient .from("users") .select("*") .eq("id", 1) .single(); return
{data?.name}
; } ``` -------------------------------- ### Initialize Browser-Side Supabase Client with Real-time in TypeScript Source: https://context7.com/advenahq/supabase-js/llms.txt Creates a Supabase client specifically for browser or client-side operations in Next.js, automatically blocking service_role access for enhanced security. It requires public Supabase URL and anonymous keys. The client can be used to subscribe to real-time changes from the database. ```typescript "use client"; import { useSupabase } from "@advenahq/supabase-js/browser"; function MyComponent() { // Initialize browser client (service_role automatically blocked) const supabase = useSupabase({ supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL as string, auth: { keys: { publishable: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY as string, }, }, }); // Subscribe to real-time updates supabase .channel("room1") .on( "postgres_changes", { event: "*", schema: "public", table: "countries" }, (payload) => { console.log("Change received!", payload); } ) .subscribe(); return
Real-time enabled
; } ``` -------------------------------- ### Supacache Provider Configuration for Caching (TypeScript) Source: https://context7.com/advenahq/supabase-js/llms.txt Demonstrates configuring the Supabase client to use Supacache for distributed edge caching, particularly with Cloudflare Workers. It shows how to initialize the client with Supacache details and use the `.cache()` method on queries to set a Time-To-Live (TTL). ```typescript import { useSupabase } from "@advenahq/supabase-js"; import type { Database } from "./database.types"; export default async function CachedPage() { const supabase = await useSupabase({ cache: { provider: "supacache", supacache: { url: "https://supacache.mycloudflareworker.workers.dev", serviceKey: process.env.SUPACACHE_SERVICE_KEY as string, }, }, supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, auth: { keys: { secret: process.env.UPV_SECRETS_SUPABASE_SERVICEROLE_KEY as string, publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY as string, }, }, }); // All queries automatically cached through Supacache middleware const { data, error } = await supabase .from("products") .cache(3600) // Cache for 1 hour .select("id, name, price") .eq("available", true); if (error) throw error; return (
{data.map((product) => (
{product.name}: ${product.price}
))}
); } ``` -------------------------------- ### Configure Supabase Client and Database Role with useSupabase Source: https://github.com/advenahq/supabase-js/blob/main/README.md This snippet illustrates configuring the Supabase client and specifying the database role for API interactions. It allows passing Supabase client options and setting the role to 'anon' or 'service_role'. This is crucial for server-side operations or when needing elevated permissions. ```typescript { /** * Configuration options for the Supabase client, passed to the Supabase client constructor. * * @link https://supabase.com/docs/reference/javascript/initializing * * @default undefined (use the default options): * - `config.db.schema` = "public" */ config?: SupabaseClientServerOptionsType | undefined; /** * The database role to use when interacting with the Supabase API. This option has no effect if `auth.useToken` is set (as the JWT supplied to useToken will contain a "role" key). * * This option is useful when you need to use a specific role for server-side operations. Using "service_role" will cause the client to use the service role key. * * Possible values: * - "anon": Use the anonymous role. * - "service_role": Use the service role. * * @default "anon" (anonymous role) */ role?: "anon" | "service_role" | undefined; // "authenticated" } ``` -------------------------------- ### Complex Supabase Query with Caching, Relations, RLS, and Auth Source: https://context7.com/advenahq/supabase-js/llms.txt Demonstrates a production-ready Supabase query pattern combining caching with Supacache, nested relationships, Row Level Security (RLS) for data access control, and authentication via environment variables. ```typescript import { useSupabase } from "@advenahq/supabase-js"; import type { Database } from "../types/database.types"; export default async function DashboardPage({ userId }: { userId: string }) { const supabase = await useSupabase({ cache: { provider: "supacache", supacache: { url: process.env.SUPACACHE_URL as string, serviceKey: process.env.SUPACACHE_SERVICE_KEY as string, }, }, role: "anon", supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, auth: { keys: { secret: process.env.UPV_SECRETS_SUPABASE_SERVICEROLE_KEY as string, publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY as string, }, }, }); // Complex query with joins, filtering, and caching const { data: projects, error } = await supabase .from("projects") .cache(1800) // Cache for 30 minutes .select( ` id, name, description, owner_id, tasks ( id, title, status, assigned_to ), team_members ( user_id, role, users ( name, email ) ) ` ) .eq("owner_id", userId) // RLS ensures user only sees their projects .eq("tasks.status", "active") .order("created_at", { ascending: false }) .limit(10); if (error) { console.error("Query failed:", error); return
Error loading dashboard
; } return (

My Projects

{projects.map((project) => (

{project.name}

Active tasks: {project.tasks.length}

Team members: {project.team_members.length}

))}
); } ``` -------------------------------- ### Apply Per-Query Caching with .cache() Method in TypeScript Source: https://context7.com/advenahq/supabase-js/llms.txt Demonstrates how to apply granular caching to individual Supabase queries using the `.cache()` method. This method allows specifying a Time-To-Live (TTL) in seconds for the cache duration. It must be called immediately after the `.from()` method. ```typescript import { useSupabase } from "@advenahq/supabase-js"; export default async function ExpensiveQueryPage() { const supabase = await useSupabase(); // Cache this expensive query for 24 hours (86400 seconds) const { data: users, error } = await supabase .from("users") .cache(86400) // Must be called immediately after .from() .select("*") .eq("status", "active"); // Cache a short-lived query for 5 minutes (300 seconds) const { data: stats, error: statsError } = await supabase .from("daily_stats") .cache(300) .select("count, date") .order("date", { ascending: false }) .limit(10); if (error || statsError) { return
Error loading data
; } return (

Active Users: {users.length}

Recent Stats: {stats.length} entries

); } ``` -------------------------------- ### Initialize Server-Side Supabase Client with Caching in TypeScript Source: https://context7.com/advenahq/supabase-js/llms.txt Initializes a Supabase client for server-side use within a Next.js project, enabling caching, authentication, and type safety. It requires Supabase credentials and a database type definition. The function returns a typed Supabase client instance. ```typescript import { useSupabase } from "@advenahq/supabase-js"; import type { Database } from "./database.types"; export default async function Page() { // Initialize with inline configuration const supabase = await useSupabase({ role: "anon", supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, auth: { keys: { secret: process.env.UPV_SECRETS_SUPABASE_SERVICEROLE_KEY as string, publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY as string, }, }, }); // Query with full type safety const { data, error } = await supabase .from("users") .select("*") .eq("id", 1) .limit(1) .single(); if (error) { console.error("Query failed:", error); return null; } return
User: {data.name}
; } ``` -------------------------------- ### Manage Access with Service Role vs Anon Role Source: https://context7.com/advenahq/supabase-js/llms.txt Illustrates how to control database access by switching between the 'service_role' (bypasses RLS) and 'anon' role (enforces RLS). This is crucial for managing administrative tasks versus public-facing data access. ```typescript import { useSupabase } from "@advenahq/supabase-js"; export default async function AdminPage() { // Service role: bypasses all RLS policies (use with caution!) const adminClient = await useSupabase({ role: "service_role", supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, auth: { keys: { secret: process.env.UPV_SECRETS_SUPABASE_SERVICEROLE_KEY as string, publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY as string, }, }, }); // Can access ALL users regardless of RLS policies const { data: allUsers } = await adminClient .from("users") .select("*"); // Anon role: enforces RLS policies const publicClient = await useSupabase({ role: "anon", supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, auth: { keys: { secret: process.env.UPV_SECRETS_SUPABASE_SERVICEROLE_KEY as string, publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY as string, }, }, }); // Only returns rows allowed by RLS policies const { data: publicUsers } = await publicClient .from("users") .select("*") .eq("is_public", true); return (

Total users (admin): {allUsers?.length}

Public users (anon): {publicUsers?.length}

); } ``` -------------------------------- ### Per-Query Caching with .cache() Method Source: https://context7.com/advenahq/supabase-js/llms.txt Allows applying granular caching to individual Supabase queries. You can specify a custom Time-To-Live (TTL) in seconds for each cached query. ```APIDOC ## Per-Query Caching with .cache() Method ### Description Apply granular caching to individual queries with custom TTL values. ### Method ```typescript .cache(ttl: number) ``` ### Parameters #### Query Parameters - **ttl** (number) - Required - The Time-To-Live for the cache in seconds. ### Request Example ```typescript import { useSupabase } from "@advenahq/supabase-js"; export default async function ExpensiveQueryPage() { const supabase = await useSupabase(); // Cache this expensive query for 24 hours (86400 seconds) const { data: users, error } = await supabase .from("users") .cache(86400) // Must be called immediately after .from() .select("*") .eq("status", "active"); // Cache a short-lived query for 5 minutes (300 seconds) const { data: stats, error: statsError } = await supabase .from("daily_stats") .cache(300) .select("count, date") .order("date", { ascending: false }) .limit(10); if (error || statsError) { return
Error loading data
; } return (

Active Users: {users.length}

Recent Stats: {stats.length} entries

); } ``` ### Response #### Success Response (200) - **data** (any) - The result of the Supabase query. - **error** (ApiError | null) - An error object if the query failed, otherwise null. #### Response Example (The response structure depends on the specific Supabase query performed. See Request Example for usage.) ``` -------------------------------- ### Configure Supabase Authentication with useSupabase Hook Source: https://github.com/advenahq/supabase-js/blob/main/README.md This snippet demonstrates how to configure authentication settings for the `useSupabase` hook. It includes options for overriding authentication with a JWT, setting a JWT secret for signing, and configuring API keys for authentication. These settings are essential for securing API requests and managing user access. ```typescript { /** * Configures the authentication options for the Supabase client. */ auth?: { /** * The JSON Web Token (JWT) to use for Row Level Security, used to construct the Authorization header. If configured, this option will override `role`, `keys.secret`, and `keys.publishable`. * * @remarks This is useful when you're using Supabase Auth and need custom claims for Row Level Security. */ useToken?: string | undefined; /** * The secret key to use for signing JWTs. * * @remarks This is used for signing JWTs for use with Supabase Auth. * @link https://supabase.com/dashboard/project/_/settings/api */ jwtSecret?: string | undefined; /** * Configures the keys to use for authenticating requests to the Supabase API. This option has no effect if `useToken` is set. */ keys?: { /** * Your Supabase installation's secret/service_role JWT (API key). This option has no effect if `auth.useToken` is set. * * @remarks This is used for server-side operations that require elevated permissions. ``` -------------------------------- ### Authenticate with Custom JWT Tokens Source: https://context7.com/advenahq/supabase-js/llms.txt Demonstrates how to use custom JWT tokens for Row Level Security (RLS) by providing specific user claims. This method allows for granular control over data access based on custom authentication logic and requires a JWT secret. ```typescript import { useSupabase } from "@advenahq/supabase-js"; import type { Database } from "./database.types"; export default async function AuthPage({ userId }: { userId: string }) { // Generate or retrieve a custom JWT with user claims const customToken = generateJWT({ sub: userId, role: "authenticated", app_metadata: { provider: "custom" }, }); // Initialize client with custom JWT (overrides role and keys) const supabase = await useSupabase({ supabaseUrl: process.env.UPV_SECRETS_SUPABASE_URL as string, auth: { useToken: customToken, // Custom JWT takes precedence jwtSecret: process.env.UPV_SECRETS_SUPABASE_JWT_SECRET as string, keys: { secret: process.env.UPV_SECRETS_SUPABASE_SERVICEROLE_KEY as string, publishable: process.env.UPV_SECRETS_SUPABASE_ANON_KEY as string, }, }, }); // Queries execute with RLS policies for the JWT's user const { data: userPosts, error } = await supabase .from("posts") .select("*") .eq("user_id", userId); // RLS automatically enforces ownership if (error) throw error; return
User posts: {userPosts.length}
; } ``` -------------------------------- ### Caching Query Responses with .cache() in Supabase JS Source: https://github.com/advenahq/supabase-js/blob/main/README.md Demonstrates how to use the `.cache()` method to cache query results for a specified duration. This method is exclusively supported for `SELECT` queries and must be placed immediately after `.from()` and before other query modifiers. It accepts a Time-To-Live (TTL) in seconds. ```tsx import { useSupabase } from "@advenahq/supabase-js"; // ... // Use the Supabase client exported by the shared configuration const supabase = await useSupabase(); // Fetch data from the users table const { data, error } = await supabase .from("users") .cache(86400) // Cache the response for 24 hours (86400 seconds = 24 hours) .select("*") .eq("id", 1); // ... ``` -------------------------------- ### Configure Supabase API Caching with useSupabase Hook Source: https://github.com/advenahq/supabase-js/blob/main/README.md This snippet shows how to configure response caching for the Supabase API within the `useSupabase` hook. It supports different caching providers like Supacache, Upstash Redis, and Node Redis, each with their specific configuration options. The `expireSetAfter` option controls the cache expiration time. ```typescript { /** * Configures the provider for caching responses from the Supabase API. */ cache?: { /** * The provider to use for caching responses from the Supabase API. * * Possible values: * - "supacache": Use a Supacache middleware service for intermediary caching. * - "upstash-redis": Use Upstash Redis for intermediary caching. * - "redis": Use Node Redis for intermediary caching. * * @default undefined (no intermediary caching) */ provider: "supacache" | "redis" | "upstash-redis" | undefined; /** * Configuration options for the Supacache (middleware) cache provider. * * @see https://github.com/AdvenaHQ/supacache */ supacache?: { /** * The URL of the Supacache middleware service. */ url: string; /** * The cache service (auth) key for the Supacache middleware service. This is the * `SUPACACHE_SERVICE_KEY` secret configured on the worker. * * @see https://github.com/AdvenaHQ/supacache?tab=readme-ov-file#middleware-worker-setup */ serviceKey?: string | undefined; }; /** * Configuration options for the Upstash Redis cache provider. */ upstash?: { /** * The URL of the Upstash Redis instance. */ url: RedisConfigNodejs["url"]; /** * The token for the Upstash Redis instance. */ token: RedisConfigNodejs["token"]; /** * The configuration options for the Upstash Redis client. */ config?: RedisConfigNodejs; /** * The behavior options for the Upstash Redis cache provider. */ behaviour?: { /** * The time, in seconds, after which cached responses should expire and be dropped from the cache. * * @default 3600 (1 hour) */ expireSetAfter?: number | undefined; }; } & RedisConfigNodejs; /** * Configuration options for the redis (ioredis) cache provider. */ ioredis?: { /** * The Connection URL of the Redis instance. */ url: string; }; }; } ``` -------------------------------- ### TypeScript Database Types Integration with Supabase Source: https://context7.com/advenahq/supabase-js/llms.txt Integrates Supabase CLI-generated types for full type safety in database queries and responses. Ensures type inference for table names, column names, and data structures, preventing runtime errors. ```typescript // types/database.types.ts - Generated by Supabase CLI export type Database = { public: { Tables: { users: { Row: { id: string; name: string; email: string; created_at: string; }; Insert: { id?: string; name: string; email: string; created_at?: string; }; Update: { id?: string; name?: string; email?: string; created_at?: string; }; }; }; }; }; // app/users.tsx import { useSupabase } from "@advenahq/supabase-js"; import type { Database } from "../types/database.types"; export default async function UsersPage() { const supabase = await useSupabase(); // Full type inference for query builder and results const { data, error } = await supabase .from("users") // TypeScript knows valid table names .select("id, name, email") // Autocomplete for column names .eq("name", "John") .single(); if (error) throw error; // data is fully typed as Database['public']['Tables']['users']['Row'] console.log(data.email); // TypeScript knows 'email' exists console.log(data.invalid); // TypeScript error: Property doesn't exist return
User: {data.name}
; } ``` -------------------------------- ### Set Supabase URL in useSupabase Hook Configuration Source: https://github.com/advenahq/supabase-js/blob/main/README.md This snippet shows the configuration for setting the Supabase API URL within the `useSupabase` hook. It highlights the `supabaseUrl` property, which is mandatory for establishing a connection to your Supabase project. The default value is derived from the environment variable `UPV_SECRETS_SUPABASE_URL`. ```typescript { /** * The URL of the Supabase API. * * @default process.env.UPV_SECRETS_SUPABASE_URL */ supabaseUrl: string; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.