Getting Started with the Supabase JavaScript Client

Supabase is an open-source Firebase alternative that offers a real-time database, authentication, and storage. This article guides you through using the Supabase JavaScript client to connect to your Supabase backend, perform CRUD operations, and handle authentication.

Installation

Install the Supabase client using npm or yarn:

npm install @supabase/supabase-js

Initialize the Client

First, import and initialize the Supabase client using your project URL and public API key:


import { createClient } from '@supabase/supabase-js'

const supabaseUrl = 'https://your-project.supabase.co'
const supabaseKey = 'public-anon-key'
const supabase = createClient(supabaseUrl, supabaseKey)

Fetching Data

You can query data from a table using the .from().select() method:


const { data, error } = await supabase
  .from('todos')
  .select('*')

if (error) console.error(error)
else console.log(data)

Inserting Data

Insert new rows into a table using .insert():


const { data, error } = await supabase
  .from('todos')
  .insert([
    { task: 'Learn Supabase', done: false }
  ])

if (error) console.error(error)
else console.log('Inserted:', data)

Updating Data

Update rows with .update() and a match condition:


const { data, error } = await supabase
  .from('todos')
  .update({ done: true })
  .eq('id', 1)

if (error) console.error(error)
else console.log('Updated:', data)

Deleting Data

Remove rows using .delete():


const { data, error } = await supabase
  .from('todos')
  .delete()
  .eq('id', 1)

if (error) console.error(error)
else console.log('Deleted:', data)

Authentication

Supabase supports various auth providers. Here's how to sign up with email and password:


const { user, error } = await supabase.auth.signUp({
  email: 'user@example.com',
  password: 'securePassword123'
})

if (error) console.error(error)
else console.log('Signed up:', user)

Listening to Changes (Real-time)

You can subscribe to changes in real-time using .channel():


const channel = supabase
  .channel('todos-updates')
  .on(
    'postgres_changes',
    { event: '*', schema: 'public', table: 'todos' },
    (payload) => {
      console.log('Change received!', payload)
    }
  )
  .subscribe()

Conclusion

The Supabase JavaScript client makes it simple to interact with your backend using familiar SQL-like operations. It supports authentication, real-time subscriptions, and file storage out of the box.

Back to top