Supabase JS: The Ultimate Guide
Hey guys! Today, we're diving deep into the world of Supabase JS. If you're building anything with JavaScript and need a solid backend, Supabase is definitely something you should check out. It's like Firebase, but open source and built on PostgreSQL. In this guide, we'll cover everything from setting up your project to advanced queries and real-time functionality. Let's get started!
What is Supabase?
Before we jump into the code, let's quickly talk about what Supabase actually is. Supabase is an open-source alternative to Firebase. It provides a suite of tools to help you build scalable and secure applications. Think of it as your backend-as-a-service (BaaS). It gives you a database (PostgreSQL), authentication, real-time subscriptions, storage, and auto-generated APIs. Essentially, it handles all the heavy lifting, so you can focus on building your frontend.
Why Use Supabase?
Okay, so why should you even bother with Supabase? Here's the lowdown:
- Open Source: You're not locked into a proprietary system.
- PostgreSQL: A powerful, reliable, and well-respected database.
- Real-time: Built-in real-time updates using WebSockets.
- Authentication: Easy user management with social logins.
- Storage: Store and serve files directly from Supabase.
- Auto-generated APIs: Supabase automatically generates RESTful APIs from your database schema.
These features are massive time-savers. Instead of spending weeks setting up a backend from scratch, you can have a fully functional one in minutes.
Setting Up Your Supabase Project
Alright, let's get our hands dirty. First, you'll need to create a project on Supabase. Head over to supabase.com and sign up. Once you're in, create a new project. You'll need to choose a name, a database password, and a region. Make sure you keep that password safe – you'll need it later. Once your project is created, Supabase will set up a PostgreSQL database for you. This usually takes a few minutes, so grab a coffee and chill.
Getting Your API Keys
While Supabase is setting up, let's grab the API keys we'll need for our JavaScript project. Go to your project dashboard and find the "API Settings" section. You'll see two important pieces of information:
- Supabase URL: This is the URL of your Supabase project.
- Supabase Anon Key: This is your project's anonymous API key.
Important: The anon key is meant to be used in client-side code. It allows read access to your database. For sensitive operations, you'll want to use the service role key (which should never be exposed in client-side code) or implement Row Level Security (RLS) to control access.
Integrating Supabase JS into Your Project
Okay, project created, API keys in hand. Now it's time to integrate Supabase JS into our JavaScript project. You can use Supabase JS in pretty much any JavaScript environment – React, Vue, Svelte, Node.js, you name it. For this guide, let's assume we're using a simple HTML file with JavaScript.
Installing Supabase JS
First, we need to include the Supabase JS library in our project. You can do this in a couple of ways:
-
CDN: Add the following script tag to your HTML file:
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>This is the easiest way to get started, but it's not recommended for production environments.
-
NPM: If you're using a build tool like Webpack or Parcel, you can install Supabase JS using NPM:
npm install @supabase/supabase-jsThen, import it into your JavaScript file:
import { createClient } from '@supabase/supabase-js'
I highly recommend using NPM for any serious project. It gives you more control over your dependencies and ensures you're using the correct version of the library.
Initializing the Supabase Client
Now that we have Supabase JS installed, we need to initialize the Supabase client. This is where we'll use the API keys we grabbed earlier. Here's how you do it:
const supabaseUrl = 'YOUR_SUPABASE_URL'
const supabaseKey = 'YOUR_SUPABASE_ANON_KEY'
const supabase = createClient(supabaseUrl, supabaseKey)
Replace YOUR_SUPABASE_URL and YOUR_SUPABASE_ANON_KEY with your actual Supabase URL and anon key. Make sure you keep these values secure!
Now, you have a supabase object that you can use to interact with your Supabase backend.
Basic CRUD Operations with Supabase JS
CRUD stands for Create, Read, Update, and Delete. These are the fundamental operations you'll be performing on your database. Let's see how to do them with Supabase JS.
Creating Data (Insert)
To insert data into your database, you'll use the insert method. First, you need to specify the table you want to insert data into. Let's say you have a table called todos with columns id, task, and completed. Here's how you can insert a new todo:
async function addTodo(task) {
const { data, error } = await supabase
.from('todos')
.insert([
{
task: task,
completed: false
}
])
if (error) {
console.error('Error inserting todo:', error)
} else {
console.log('Todo inserted successfully:', data)
}
}
addTodo('Learn Supabase JS')
Explanation:
supabase.from('todos'): Specifies thetodostable.insert([{ task: task, completed: false }]): Inserts a new row with the given values.await: We useawaitbecause theinsertmethod is asynchronous.dataanderror: Theinsertmethod returns an object withdataanderrorproperties. If the insertion was successful,datawill contain the inserted row. If there was an error,errorwill contain the error message.
Reading Data (Select)
To read data from your database, you'll use the select method. You can specify which columns you want to select, and you can also add filters to narrow down your results. Here's how you can select all todos:
async function getTodos() {
const { data: todos, error } = await supabase
.from('todos')
.select('*')
if (error) {
console.error('Error getting todos:', error)
} else {
console.log('Todos:', todos)
}
}
getTodos()
Explanation:
supabase.from('todos'): Specifies thetodostable.select('*'): Selects all columns from the table.data: todos: Renames thedataproperty totodosfor clarity.
To add a filter, you can use the eq method. For example, to select only the completed todos:
async function getCompletedTodos() {
const { data: todos, error } = await supabase
.from('todos')
.select('*')
.eq('completed', true)
if (error) {
console.error('Error getting completed todos:', error)
} else {
console.log('Completed todos:', todos)
}
}
getCompletedTodos()
Updating Data (Update)
To update data in your database, you'll use the update method. You need to specify the table you want to update, the values you want to update, and a filter to identify the row you want to update. Here's how you can update a todo to mark it as completed:
async function updateTodo(id, completed) {
const { data, error } = await supabase
.from('todos')
.update({ completed: completed })
.eq('id', id)
if (error) {
console.error('Error updating todo:', error)
} else {
console.log('Todo updated successfully:', data)
}
}
updateTodo(1, true)
Explanation:
supabase.from('todos'): Specifies thetodostable.update({ completed: completed }): Sets thecompletedcolumn to the given value.eq('id', id): Filters the row to update based on theidcolumn.
Deleting Data (Delete)
To delete data from your database, you'll use the delete method. You need to specify the table you want to delete from and a filter to identify the row you want to delete. Here's how you can delete a todo:
async function deleteTodo(id) {
const { data, error } = await supabase
.from('todos')
.delete()
.eq('id', id)
if (error) {
console.error('Error deleting todo:', error)
} else {
console.log('Todo deleted successfully:', data)
}
}
deleteTodo(1)
Explanation:
supabase.from('todos'): Specifies thetodostable.delete(): Deletes the row.eq('id', id): Filters the row to delete based on theidcolumn.
Real-time Subscriptions
One of the coolest features of Supabase is its real-time functionality. You can subscribe to changes in your database and receive updates in real-time using WebSockets. This is perfect for building collaborative applications, chat apps, and anything else that needs to react to data changes instantly.
Setting Up Real-time
First, you need to enable real-time subscriptions in your Supabase project. Go to your project dashboard and find the "Realtime" section. Enable the real-time server. Then, you need to define which tables and columns you want to subscribe to. This is done using policies. For example, to allow everyone to subscribe to changes in the todos table, you can create a policy like this:
CREATE POLICY "Enable ALL for everyone" ON public.todos
AS PERMISSIVE
FOR ALL
TO public
USING (true);
Important: Be careful with your real-time policies. You don't want to accidentally expose sensitive data to unauthorized users.
Subscribing to Changes
Once you've enabled real-time and defined your policies, you can subscribe to changes in your JavaScript code. Here's how you do it:
supabase
.channel('any')
.on(
'postgres_changes',
{ event: '*', schema: 'public', table: 'todos' },
(payload) => {
console.log('Change received!', payload)
}
)
.subscribe()
Explanation:
supabase.channel('any'): Creates a new real-time channel..on('postgres_changes', ...): Subscribes to PostgreSQL changes.event: '*': Listens for all events (INSERT, UPDATE, DELETE).schema: 'public': Specifies the schema to listen to.table: 'todos': Specifies the table to listen to.payload: Contains the data that changed..subscribe(): Starts the subscription.
Now, whenever a todo is created, updated, or deleted, you'll receive a payload object with the details of the change. You can use this information to update your UI in real-time.
Authentication with Supabase JS
Authentication is a crucial part of most web applications. Supabase provides a built-in authentication system that makes it easy to manage users and control access to your data. It supports email/password authentication, social logins (Google, GitHub, etc.), and more.
Setting Up Authentication
To set up authentication, go to your Supabase project dashboard and find the "Authentication" section. Enable the authentication providers you want to use. For example, to enable email/password authentication, simply toggle the "Email Sign-in" option. For social logins, you'll need to configure the provider with your application's credentials.
Signing Up Users
To sign up a new user with email and password, you can use the signUp method:
async function signUp(email, password) {
const { data, error } = await supabase.auth.signUp({
email: email,
password: password
})
if (error) {
console.error('Error signing up:', error)
} else {
console.log('User signed up successfully:', data)
}
}
signUp('test@example.com', 'password123')
Explanation:
supabase.auth.signUp(...): Signs up a new user.email: The user's email address.password: The user's password.
Signing In Users
To sign in an existing user with email and password, you can use the signInWithPassword method:
async function signIn(email, password) {
const { data, error } = await supabase.auth.signInWithPassword({
email: email,
password: password
})
if (error) {
console.error('Error signing in:', error)
} else {
console.log('User signed in successfully:', data)
}
}
signIn('test@example.com', 'password123')
Explanation:
supabase.auth.signInWithPassword(...): Signs in an existing user.email: The user's email address.password: The user's password.
Signing Out Users
To sign out the current user, you can use the signOut method:
async function signOut() {
const { error } = await supabase.auth.signOut()
if (error) {
console.error('Error signing out:', error)
} else {
console.log('User signed out successfully')
}
}
signOut()
Getting the Current User
To get the current user, you can use the getUser method:
async function getCurrentUser() {
const { data: { user }, error } = await supabase.auth.getUser()
if (error) {
console.error('Error getting user:', error)
} else {
console.log('Current user:', user)
}
}
getCurrentUser()
Conclusion
So, there you have it! A comprehensive guide to Supabase JS. We've covered everything from setting up your project to performing CRUD operations, real-time subscriptions, and authentication. Supabase is an incredibly powerful tool that can save you a ton of time and effort when building web applications. I hope this guide has been helpful. Now go out there and build something awesome!