DEV Community

Cover image for What is Supabase? How to Integrate It with Your React Application
Jehnsen Enrique
Jehnsen Enrique

Posted on • Updated on

What is Supabase? How to Integrate It with Your React Application

As a developer, you're always looking for efficient, powerful tools to streamline your workflow and enhance your applications. Enter Supabase, an open-source alternative to Firebase that leverages the power of PostgreSQL databases. In this blog post, we'll explore what Supabase is, its standout features, and how you can seamlessly integrate it with a React application. Let's dive in!

🔋What is Supabase?

Supabase is an open-source backend-as-a-service (BaaS) that provides developers with a scalable, real-time backend in just a few clicks. It offers a comprehensive suite of tools, including a managed PostgreSQL database, real-time data synchronization, authentication, storage, and serverless functions. Supabase is designed to simplify backend development, allowing you to focus on building your application rather than managing infrastructure.

Key Features of Supabase

PostgreSQL Database

  • Fully managed PostgreSQL database with instant APIs.
  • Supports advanced queries, full-text search, and JSON data types.
  • Row-level security for fine-grained access control.

Authentication

  • Built-in support for user authentication and authorization.
  • Email and password login, social logins (Google, GitHub, etc.), and magic link login.
  • JWT-based session management.

Real-time

  • Enables real-time data synchronization using PostgreSQL's replication features.
  • Build collaborative applications that react instantly to changes in the database.

Storage

  • Secure file storage with a simple API.
  • Public and private buckets with access control using policies.

Edge Functions

  • Write and deploy serverless functions that run close to your users.
  • Low-latency execution and easy integration with your Supabase project.

Integrating Supabase with a React Application

Now that we've covered what Supabase offers, let's see how to integrate it into a React application. We'll create a simple React app that uses Supabase for authentication and data management.

Step 1: Set Up Supabase

✔️Create a Supabase Project:
  • Go to Supabase and sign up for an account.
  • Create a new project and note down the Project URL and API Key.
✔️Set Up a Database Table:
  • Navigate to the "Table Editor" in the Supabase dashboard.
  • Create a new table (e.g., todos) with columns for id, task, and is_complete.

Step 2: Set Up the React Application

✔️Create a React App:
npx create-react-app supabase-react-app
cd supabase-react-app
Enter fullscreen mode Exit fullscreen mode
✔️Install Supabase Client:
npm install @supabase/supabase-js
Enter fullscreen mode Exit fullscreen mode
✔️Configure Supabase Client:

Create a file named supabaseClient.js in the src directory:

// src/supabaseClient.js
import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'https://your-project-ref.supabase.co';
const supabaseKey = 'your-anon-key';

const supabase = createClient(supabaseUrl, supabaseKey);

export default supabase;
Enter fullscreen mode Exit fullscreen mode

Step 3: Implement Authentication

✔️Create a Login Component:
// src/Login.js
import React, { useState } from 'react';
import supabase from './supabaseClient';

const Login = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = async (e) => {
    e.preventDefault();
    const { user, error } = await supabase.auth.signIn({ email, password });
    if (error) console.error('Error logging in:', error.message);
    else console.log('Logged in user:', user);
  };

  return (
    <form onSubmit={handleLogin}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
        required
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
        required
      />
      <button type="submit">Login</button>
    </form>
  );
}

export default Login;
Enter fullscreen mode Exit fullscreen mode
✔️Create a Logout Function:
// src/Logout.js
import React from 'react';
import supabase from './supabaseClient';

const Logout = () => {
  const handleLogout = async () => {
    const { error } = await supabase.auth.signOut();
    if (error) console.error('Error logging out:', error.message);
  };

  return <button onClick={handleLogout}>Logout</button>;
}

export default Logout;
Enter fullscreen mode Exit fullscreen mode

Step 4: Manage Data

✔️Create a Todo Component:
// src/Todo.js
import React, { useState, useEffect } from 'react';
import supabase from './supabaseClient';

const Todo = () => {
  const [todos, setTodos] = useState([]);
  const [newTask, setNewTask] = useState('');

  useEffect(() => {
    fetchTodos();
  }, []);

  const fetchTodos = async () => {
    let { data: todos, error } = await supabase.from('todos').select('*');
    if (error) console.error('Error fetching todos:', error.message);
    else setTodos(todos);
  };

  const addTodo = async () => {
    const { data, error } = await supabase.from('todos').insert([{ task: newTask, is_complete: false }]);
    if (error) console.error('Error adding todo:', error.message);
    else setTodos([...todos, data[0]]);
    setNewTask('');
  };

  return (
    <div>
      <h1>Todo List</h1>
      <input
        type="text"
        value={newTask}
        onChange={(e) => setNewTask(e.target.value)}
        placeholder="New Task"
      />
      <button onClick={addTodo}>Add Task</button>
      <ul>
        {todos.map(todo => (
          <li key={todo.id}>{todo.task}</li>
        ))}
      </ul>
    </div>
  );
}

export default Todo;
Enter fullscreen mode Exit fullscreen mode

Step 5: Combine Everything in App Component

✔️Update App Component:
// src/App.js
import React, { useState, useEffect } from 'react';
import supabase from './supabaseClient';
import Login from './Login';
import Logout from './Logout';
import Todo from './Todo';

function App() {
  const [session, setSession] = useState(null);

  useEffect(() => {
    const session = supabase.auth.session();
    setSession(session);

    supabase.auth.onAuthStateChange((_event, session) => {
      setSession(session);
    });
  }, []);

  return (
    <div className="App">
      <h1>Supabase + React</h1>
      {!session ? (
        <Login />
      ) : (
        <>
          <Logout />
          <Todo />
        </>
      )}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Conclusion

Supabase is a powerful, open-source backend-as-a-service that simplifies the process of building and scaling web applications. By integrating Supabase with your React application, you can leverage its real-time data synchronization, authentication, and storage capabilities to build robust, scalable apps quickly and efficiently.

Give Supabase a try for your next project, and experience the ease of building modern web applications with a powerful backend solution. Happy coding! 🙂


Docs:
Supabase
React

Top comments (0)