- Published on
Getting Started with Supabase in React.js
- Authors
- Name
- codewithininsight
- @
Supabase is an open-source alternative to Firebase that provides backend features like PostgreSQL databases, authentication, storage, and real-time updates. In this guide, we’ll explore how to integrate Supabase with a React.js application.
What You’ll Learn
- Setting up Supabase in a React app.
- Performing CRUD operations.
- Adding user authentication.
- Enabling real-time updates.
Step 1: Create a Supabase Project
- Go to the Supabase Dashboard.
- Sign up or log in, and create a new project.
- Configure:
- A project name.
- A secure database password.
- A region close to your users.
Step 2: Install Supabase Client
To use Supabase in React, install the official JavaScript library:
npm install @supabase/supabase-js
Step 3: Initialize Supabase Client
Create a file supabaseClient.js
in your project to configure the Supabase client:
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = process.env.REACT_APP_SUPABASE_URL
const supabaseAnonKey = process.env.REACT_APP_SUPABASE_ANON_KEY
export const supabase = createClient(supabaseUrl, supabaseAnonKey)
Add your Supabase keys to a .env
file:
REACT_APP_SUPABASE_URL=https://your-project.supabase.co
REACT_APP_SUPABASE_ANON_KEY=your-anonymous-key
Step 4: Fetch Data in React
Let’s fetch data from a Supabase table named posts
:
import { useEffect, useState } from 'react'
import { supabase } from './supabaseClient'
export default function App() {
const [posts, setPosts] = useState([])
useEffect(() => {
const fetchPosts = async () => {
const { data, error } = await supabase.from('posts').select('*')
if (error) {
console.error('Error fetching posts:', error)
} else {
setPosts(data)
}
}
fetchPosts()
}, [])
return (
<div>
<h1>Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
)
}
Step 5: Insert Data
Here’s how you can add new records to the posts
table:
const addPost = async () => {
const { data, error } = await supabase
.from('posts')
.insert([{ title: 'New Post', content: 'This is the content of the new post.' }])
if (error) {
console.error('Error adding post:', error)
} else {
console.log('Post added:', data)
}
}
Step 6: User Authentication
Sign Up Users
const signUp = async (email, password) => {
const { user, error } = await supabase.auth.signUp({ email, password })
if (error) {
console.error('Sign up error:', error)
} else {
console.log('User signed up:', user)
}
}
Login Users
const login = async (email, password) => {
const { user, error } = await supabase.auth.signInWithPassword({ email, password })
if (error) {
console.error('Login error:', error)
} else {
console.log('User logged in:', user)
}
}
Step 7: Real-Time Updates
Enable real-time updates to listen for changes in the posts
table:
import { useEffect } from 'react'
import { supabase } from './supabaseClient'
export default function RealTimePosts() {
useEffect(() => {
const subscription = supabase
.from('posts')
.on('INSERT', (payload) => {
console.log('New post added:', payload.new)
})
.subscribe()
return () => {
supabase.removeSubscription(subscription)
}
}, [])
return <div>Listening for new posts...</div>
}
Step 8: Run Your React App
npm run
Conclusion
Supabase makes it simple to build scalable, real-time, and feature-rich applications in React.js. By leveraging its powerful backend features, you can save development time and focus on delivering great user experiences.
Key Takeaways:
- Set up a database, authentication, and real-time features easily.
- Perform CRUD operations with a straightforward API.
- Enable real-time updates for dynamic applications.
For more information, check out the Supabase Documentation.