Installation
Install the Supabase JavaScript client library:
npm install @supabase/supabase-js
Initializing
Create a single supabase client for interacting with your database.
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = process.env.SUPABASE_URL
const supabaseKey = process.env.SUPABASE_ANON_KEY
const supabase = createClient(supabaseUrl, supabaseKey)
The unique Supabase URL for your project.
The Supabase anon key or service role key for your project.
Optional configuration parameters.
Authentication options.
Automatically refresh the token before expiring.
Whether to persist the user session to local storage.
Detect OAuth grants in the URL and sign in automatically.
Realtime options.
Custom parameters to pass to the Realtime connection.
Global configuration options.
Custom headers to send with every request.
Custom fetch implementation.
Database Operations
Select Data
Query data from your tables.
const { data, error } = await supabase
.from('countries')
.select('*')
The returned rows from the query.
Error object if the query failed, null otherwise.
Select with Filters
const { data, error } = await supabase
.from('countries')
.select('name, capital')
.eq('id', 1)
.single()
Select with Joins
const { data, error } = await supabase
.from('countries')
.select(`
name,
cities (
name,
population
)
`)
Insert Data
Insert rows into your tables.
const { data, error } = await supabase
.from('countries')
.insert([
{ name: 'Denmark', code: 'DK' },
{ name: 'Norway', code: 'NO' }
])
.select()
The values to insert. Can be a single object or an array of objects.
The inserted rows (if .select() is used).
Error object if the insert failed, null otherwise.
Update Data
Update existing rows in your tables.
const { data, error } = await supabase
.from('countries')
.update({ name: 'Australia' })
.eq('id', 1)
.select()
Upsert Data
Insert or update rows based on unique constraints.
const { data, error } = await supabase
.from('countries')
.upsert({ id: 1, name: 'Australia' })
.select()
Delete Data
Delete rows from your tables.
const { data, error } = await supabase
.from('countries')
.delete()
.eq('id', 1)
Authentication
Sign Up
Create a new user account.
const { data, error } = await supabase.auth.signUp({
email: '[email protected]',
password: 'example-password',
})
The user’s email address.
Optional parameters.
Additional user metadata.
A URL to redirect to after signup.
Captcha token for verification.
Error object if signup failed, null otherwise.
Sign In
Sign in an existing user.
const { data, error } = await supabase.auth.signInWithPassword({
email: '[email protected]',
password: 'example-password',
})
Sign Out
Sign out the current user.
const { error } = await supabase.auth.signOut()
Get Session
Get the current session.
const { data: { session } } = await supabase.auth.getSession()
The current session object or null if no active session.
Get User
Get the current user.
const { data: { user } } = await supabase.auth.getUser()
The current user object or null if not authenticated.
Storage
Upload File
Upload a file to a storage bucket.
const { data, error } = await supabase.storage
.from('avatars')
.upload('public/avatar1.png', file, {
contentType: 'image/png'
})
The file path including the file name.
fileBody
File | Blob | ArrayBuffer
required
The file data to upload.
Upload options.
Cache control header value.
When true, overwrites existing file with the same path.
Download File
Download a file from storage.
const { data, error } = await supabase.storage
.from('avatars')
.download('public/avatar1.png')
The file path to download.
List Files
List all files in a bucket.
const { data, error } = await supabase.storage
.from('avatars')
.list('public', {
limit: 100,
offset: 0,
sortBy: { column: 'name', order: 'asc' }
})
Delete Files
Delete files from storage.
const { data, error } = await supabase.storage
.from('avatars')
.remove(['public/avatar1.png', 'public/avatar2.png'])
Get Public URL
Get the public URL for a file.
const { data } = supabase.storage
.from('avatars')
.getPublicUrl('public/avatar1.png')
console.log(data.publicUrl)
Realtime
Subscribe to Changes
Listen to database changes in realtime.
const channel = supabase
.channel('db-changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'countries'
},
(payload) => {
console.log('Change received!', payload)
}
)
.subscribe()
The database event to listen for: INSERT, UPDATE, DELETE, or * for all.
The database schema to listen to.
Optional filter for the change events (e.g., id=eq.1).
Unsubscribe
Stop listening to changes.
await supabase.removeChannel(channel)
Edge Functions
Invoke Function
Invoke a Supabase Edge Function.
const { data, error } = await supabase.functions.invoke('hello-world', {
body: { name: 'Functions' }
})
The name of the Edge Function to invoke.
Function invocation options.
The request body to send to the function.
Custom headers to send with the request.
The response data from the function.
Error object if invocation failed, null otherwise.
TypeScript Support
Generate TypeScript types from your database schema:
import { createClient } from '@supabase/supabase-js'
import { Database } from './types/supabase'
const supabase = createClient<Database>(
process.env.SUPABASE_URL!,
process.env.SUPABASE_ANON_KEY!
)
// Now all queries are fully typed
const { data } = await supabase
.from('countries')
.select('*')
.eq('id', 1)
.single()
Error Handling
All methods return an error object if something goes wrong:
const { data, error } = await supabase
.from('countries')
.select('*')
if (error) {
console.error('Error:', error.message)
return
}
console.log('Data:', data)
Additional Resources
GitHub Repository
View the source code and contribute
NPM Package
View package details and versions