0
# Supabase JavaScript Client
1
2
Supabase JavaScript Client is an isomorphic TypeScript library that provides a unified interface for interacting with Supabase services. It enables developers to work with authentication, PostgreSQL databases, real-time subscriptions, file storage, and edge functions from any JavaScript runtime environment including browsers, Node.js, Deno, Bun, and React Native.
3
4
## Package Information
5
6
- **Package Name**: @supabase/supabase-js
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @supabase/supabase-js`
10
11
## Core Imports
12
13
```typescript
14
import { createClient, SupabaseClient } from "@supabase/supabase-js";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { createClient, SupabaseClient } = require("@supabase/supabase-js");
21
```
22
23
UMD (browser):
24
25
```html
26
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
27
<script>
28
const { createClient } = supabase;
29
</script>
30
```
31
32
Deno:
33
34
```typescript
35
import { createClient } from "jsr:@supabase/supabase-js@2";
36
```
37
38
## Basic Usage
39
40
```typescript
41
import { createClient } from "@supabase/supabase-js";
42
43
// Create a single supabase client for interacting with your database
44
const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key');
45
46
// Example: Select data from a table
47
const { data, error } = await supabase
48
.from('countries')
49
.select('*');
50
51
// Example: Insert data
52
const { data, error } = await supabase
53
.from('countries')
54
.insert([
55
{ name: 'Denmark' }
56
]);
57
58
// Example: Listen for real-time changes
59
const channel = supabase
60
.channel('countries-channel')
61
.on('postgres_changes',
62
{ event: '*', schema: 'public', table: 'countries' },
63
(payload) => {
64
console.log('Change received!', payload);
65
}
66
)
67
.subscribe();
68
```
69
70
## Architecture
71
72
The Supabase client is built around several key components:
73
74
- **SupabaseClient**: Main client class that orchestrates all services
75
- **Database Client**: PostgreSQL operations via PostgREST API (`from()`, `rpc()`, `schema()`)
76
- **Authentication**: User management and session handling via `auth` property
77
- **Real-time**: WebSocket-based subscriptions via `realtime` and `channel()` methods
78
- **Storage**: File upload/download operations via `storage` property
79
- **Edge Functions**: Serverless function invocation via `functions` property
80
- **Type Safety**: Full TypeScript support with database schema typing
81
82
## Client Factory Function
83
84
```typescript { .api }
85
/**
86
* Creates a new Supabase Client instance
87
* @param supabaseUrl - The unique Supabase URL for your project
88
* @param supabaseKey - The unique Supabase Key for your project
89
* @param options - Optional configuration for the client
90
* @returns Configured SupabaseClient instance
91
*/
92
function createClient<
93
Database = any,
94
SchemaNameOrClientOptions extends string | { PostgrestVersion: string } = 'public',
95
SchemaName extends string = SchemaNameOrClientOptions extends string
96
? SchemaNameOrClientOptions
97
: 'public'
98
>(
99
supabaseUrl: string,
100
supabaseKey: string,
101
options?: SupabaseClientOptions<SchemaName>
102
): SupabaseClient<Database, SchemaNameOrClientOptions, SchemaName>;
103
104
interface SupabaseClientOptions<SchemaName> {
105
/** Database configuration */
106
db?: {
107
/** The Postgres schema which your tables belong to. Defaults to 'public' */
108
schema?: SchemaName;
109
};
110
/** Authentication configuration */
111
auth?: {
112
/** Automatically refreshes the token for logged-in users. Defaults to true */
113
autoRefreshToken?: boolean;
114
/** Optional key name used for storing tokens in local storage */
115
storageKey?: string;
116
/** Whether to persist a logged-in session to storage. Defaults to true */
117
persistSession?: boolean;
118
/** Detect a session from the URL. Used for OAuth login callbacks. Defaults to true */
119
detectSessionInUrl?: boolean;
120
/** A storage provider. Used to store the logged-in session */
121
storage?: SupabaseAuthClientOptions['storage'];
122
/** OAuth flow to use - defaults to implicit flow. PKCE is recommended for mobile and server-side applications */
123
flowType?: SupabaseAuthClientOptions['flowType'];
124
/** If debug messages for authentication client are emitted */
125
debug?: SupabaseAuthClientOptions['debug'];
126
};
127
/** Options passed to the realtime-js instance */
128
realtime?: RealtimeClientOptions;
129
/** Storage client configuration */
130
storage?: StorageClientOptions;
131
/** Global configuration */
132
global?: {
133
/** A custom fetch implementation */
134
fetch?: Fetch;
135
/** Optional headers for initializing the client */
136
headers?: Record<string, string>;
137
};
138
/** Optional function for using a third-party authentication system with Supabase */
139
accessToken?: () => Promise<string | null>;
140
}
141
```
142
143
## Capabilities
144
145
### Database Operations
146
147
Core PostgreSQL database operations including table queries, function calls, and schema switching. Provides type-safe query building with filtering, ordering, and pagination.
148
149
```typescript { .api }
150
// Query builder for tables and views
151
from<TableName extends string>(relation: TableName): PostgrestQueryBuilder;
152
153
// Database function calls
154
rpc<FnName extends string>(
155
fn: FnName,
156
args?: Record<string, any>,
157
options?: {
158
head?: boolean;
159
get?: boolean;
160
count?: 'exact' | 'planned' | 'estimated';
161
}
162
): PostgrestFilterBuilder;
163
164
// Schema switching
165
schema<DynamicSchema extends string>(schema: DynamicSchema): PostgrestClient;
166
```
167
168
[Database Operations](./database.md)
169
170
### Authentication
171
172
Complete user management system with email/password, OAuth providers, magic links, and session management. Includes user registration, login, logout, and profile management.
173
174
```typescript { .api }
175
interface SupabaseAuthClient {
176
// Session management
177
getSession(): Promise<{ data: { session: Session | null }, error: AuthError | null }>;
178
getUser(): Promise<{ data: { user: User | null }, error: AuthError | null }>;
179
180
// Authentication methods
181
signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse>;
182
signInWithPassword(credentials: SignInWithPasswordCredentials): Promise<AuthResponse>;
183
signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<{ data: { url: string }, error: AuthError | null }>;
184
signOut(): Promise<{ error: AuthError | null }>;
185
186
// Event handling
187
onAuthStateChange(
188
callback: (event: AuthChangeEvent, session: Session | null) => void
189
): { data: { subscription: Subscription } };
190
}
191
```
192
193
[Authentication](./authentication.md)
194
195
### Real-time Subscriptions
196
197
WebSocket-based real-time functionality for database changes, broadcast messages, and presence tracking. Enables live updates for collaborative applications.
198
199
```typescript { .api }
200
// Create channels for real-time communication
201
channel(name: string, opts?: RealtimeChannelOptions): RealtimeChannel;
202
203
// Channel management
204
getChannels(): RealtimeChannel[];
205
removeChannel(channel: RealtimeChannel): Promise<'ok' | 'timed out' | 'error'>;
206
removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]>;
207
208
interface RealtimeChannel {
209
// Database change subscriptions
210
on(
211
type: 'postgres_changes',
212
filter: { event: string; schema: string; table?: string; filter?: string },
213
callback: (payload: any) => void
214
): RealtimeChannel;
215
216
// Broadcast messaging
217
on(type: 'broadcast', filter: { event: string }, callback: (payload: any) => void): RealtimeChannel;
218
219
// Presence tracking
220
on(type: 'presence', filter: { event: string }, callback: (payload: any) => void): RealtimeChannel;
221
222
subscribe(): RealtimeChannel;
223
unsubscribe(): Promise<'ok' | 'timed out' | 'error'>;
224
}
225
```
226
227
[Real-time](./realtime.md)
228
229
### File Storage
230
231
File upload, download, and management system with access policies, image transformations, and CDN integration. Supports any file type with configurable permissions.
232
233
```typescript { .api }
234
interface SupabaseStorageClient {
235
// Bucket operations
236
listBuckets(): Promise<{ data: Bucket[] | null, error: StorageError | null }>;
237
createBucket(id: string, options?: BucketOptions): Promise<{ data: Bucket | null, error: StorageError | null }>;
238
getBucket(id: string): Promise<{ data: Bucket | null, error: StorageError | null }>;
239
240
// File operations
241
from(bucketId: string): FileApi;
242
}
243
244
interface FileApi {
245
upload(path: string, fileBody: File | ArrayBuffer | string, options?: FileOptions): Promise<{ data: FileObject | null, error: StorageError | null }>;
246
download(path: string): Promise<{ data: Blob | null, error: StorageError | null }>;
247
list(path?: string, options?: SearchOptions): Promise<{ data: FileObject[] | null, error: StorageError | null }>;
248
remove(paths: string[]): Promise<{ data: FileObject[] | null, error: StorageError | null }>;
249
}
250
```
251
252
[Storage](./storage.md)
253
254
### Edge Functions
255
256
Serverless function invocation system for running custom business logic at the edge. Supports function calls with custom headers, authentication, and region selection.
257
258
```typescript { .api }
259
interface FunctionsClient {
260
invoke<T = any>(
261
functionName: string,
262
options?: FunctionInvokeOptions
263
): Promise<FunctionResponse<T>>;
264
}
265
266
interface FunctionInvokeOptions {
267
headers?: Record<string, string>;
268
body?: any;
269
region?: FunctionRegion;
270
}
271
272
interface FunctionResponse<T> {
273
data: T | null;
274
error: FunctionsError | null;
275
}
276
277
enum FunctionRegion {
278
Any = 'any',
279
ApNortheast1 = 'ap-northeast-1',
280
ApSoutheast1 = 'ap-southeast-1',
281
ApSouth1 = 'ap-south-1',
282
CaCentral1 = 'ca-central-1',
283
EuCentral1 = 'eu-central-1',
284
EuWest1 = 'eu-west-1',
285
EuWest2 = 'eu-west-2',
286
SaEast1 = 'sa-east-1',
287
UsEast1 = 'us-east-1',
288
UsWest1 = 'us-west-1',
289
UsWest2 = 'us-west-2'
290
}
291
```
292
293
[Edge Functions](./functions.md)
294
295
## Core Types
296
297
```typescript { .api }
298
// Main client class
299
class SupabaseClient<Database = any, SchemaNameOrClientOptions = 'public', SchemaName = 'public'> {
300
auth: SupabaseAuthClient;
301
realtime: RealtimeClient;
302
storage: SupabaseStorageClient;
303
readonly functions: FunctionsClient;
304
305
constructor(
306
supabaseUrl: string,
307
supabaseKey: string,
308
options?: SupabaseClientOptions<SchemaName>
309
);
310
}
311
312
// Type alias for Fetch
313
type Fetch = typeof fetch;
314
315
// Helper types for query results
316
type QueryResult<T> = T extends PromiseLike<infer U> ? U : never;
317
type QueryData<T> = T extends PromiseLike<{ data: infer U }> ? Exclude<U, null> : never;
318
type QueryError = PostgrestError;
319
320
// Schema type definitions
321
interface GenericTable {
322
Row: Record<string, unknown>;
323
Insert: Record<string, unknown>;
324
Update: Record<string, unknown>;
325
Relationships: GenericRelationship[];
326
}
327
328
interface GenericView {
329
Row: Record<string, unknown>;
330
Relationships: GenericRelationship[];
331
}
332
333
interface GenericFunction {
334
Args: Record<string, unknown>;
335
Returns: unknown;
336
}
337
338
interface GenericSchema {
339
Tables: Record<string, GenericTable>;
340
Views: Record<string, GenericView>;
341
Functions: Record<string, GenericFunction>;
342
}
343
344
interface GenericRelationship {
345
foreignKeyName: string;
346
columns: string[];
347
isOneToOne?: boolean;
348
referencedRelation: string;
349
referencedColumns: string[];
350
}
351
```
352
353
## Re-exported Types
354
355
The client re-exports key types from its dependencies for convenience:
356
357
```typescript { .api }
358
// From @supabase/auth-js
359
export type AuthUser = User;
360
export type AuthSession = Session;
361
export * from '@supabase/auth-js';
362
363
// From @supabase/postgrest-js
364
export type PostgrestResponse<T> = PostgrestResponse<T>;
365
export type PostgrestSingleResponse<T> = PostgrestSingleResponse<T>;
366
export type PostgrestMaybeSingleResponse<T> = PostgrestMaybeSingleResponse<T>;
367
export type PostgrestError = PostgrestError;
368
369
// From @supabase/functions-js
370
export type FunctionsHttpError = FunctionsHttpError;
371
export type FunctionsFetchError = FunctionsFetchError;
372
export type FunctionsRelayError = FunctionsRelayError;
373
export type FunctionsError = FunctionsError;
374
export type FunctionInvokeOptions = FunctionInvokeOptions;
375
export type FunctionRegion = FunctionRegion;
376
377
// From @supabase/realtime-js
378
export * from '@supabase/realtime-js';
379
```