Supabase Integration

Connect your Next.js app with Supabase backend

🚀 What is Supabase?

Supabase is an open-source Firebase alternative providing database, authentication, storage, and real-time subscriptions. It integrates seamlessly with Next.js for building full-stack applications quickly and efficiently.


// Install Supabase client
npm install @supabase/supabase-js

// Basic Supabase setup
import { createClient } from '@supabase/supabase-js'

const supabase = createClient(
  'YOUR_SUPABASE_URL',
  'YOUR_SUPABASE_KEY'
)
                                    

Key Supabase Features

🗄️

Database

PostgreSQL database with instant APIs

const { data } = await supabase
  .from('users')
  .select('*')
🔐

Authentication

Built-in user authentication system

await supabase.auth
  .signUp({
    email, password
  })
📦

Storage

File storage for images and assets

await supabase.storage
  .from('avatars')
  .upload(path, file)

Real-time

Live data updates and subscriptions

supabase
  .channel('messages')
  .on('INSERT', callback)
  .subscribe()

🔹 Setting Up Supabase Client

Create a Supabase client to interact with your backend. This configuration allows you to access database, authentication, and storage features throughout your Next.js application.

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

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY

export const supabase = createClient(supabaseUrl, supabaseKey)

Environment Variables (.env.local):

NEXT_PUBLIC_SUPABASE_URL=your-project-url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key

🔹 Fetching Data from Database

Query your Supabase database using simple JavaScript methods. Supabase automatically generates APIs for all your tables, making data fetching straightforward and type-safe.

// app/page.js
'use client'
import { useEffect, useState } from 'react'
import { supabase } from '@/lib/supabase'

export default function Home() {
  const [posts, setPosts] = useState([])

  useEffect(() => {
    async function fetchPosts() {
      const { data } = await supabase
        .from('posts')
        .select('*')
        .order('created_at', { ascending: false })
      
      setPosts(data)
    }
    fetchPosts()
  }, [])

  return (
    <div>
      {posts.map(post => (
        <div key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.content}</p>
        </div>
      ))}
    </div>
  )
}

🔹 User Authentication

Implement secure user authentication with email and password. Supabase handles password hashing, session management, and security best practices automatically for your application.

// components/LoginForm.js
'use client'
import { useState } from 'react'
import { supabase } from '@/lib/supabase'

export default function LoginForm() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  const handleLogin = async (e) => {
    e.preventDefault()
    const { data, error } = await supabase.auth.signInWithPassword({
      email,
      password
    })
    
    if (error) alert(error.message)
    else alert('Login successful!')
  }

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

🔹 Inserting Data

Add new records to your database with simple insert operations. Supabase validates data against your table schema and returns the newly created record.

// Creating a new post
async function createPost(title, content) {
  const { data, error } = await supabase
    .from('posts')
    .insert([
      { title, content, user_id: userId }
    ])
    .select()

  if (error) console.error(error)
  else console.log('Post created:', data)
}

// Usage
createPost('My First Post', 'Hello Supabase!')

🔹 Real-time Subscriptions

Listen to database changes in real-time. Perfect for chat applications, live notifications, or collaborative features where multiple users need instant updates.

// components/RealtimeMessages.js
'use client'
import { useEffect, useState } from 'react'
import { supabase } from '@/lib/supabase'

export default function RealtimeMessages() {
  const [messages, setMessages] = useState([])

  useEffect(() => {
    // Subscribe to new messages
    const channel = supabase
      .channel('messages')
      .on('postgres_changes', 
        { event: 'INSERT', schema: 'public', table: 'messages' },
        (payload) => {
          setMessages(prev => [...prev, payload.new])
        }
      )
      .subscribe()

    return () => {
      supabase.removeChannel(channel)
    }
  }, [])

  return (
    <div>
      {messages.map(msg => (
        <p key={msg.id}>{msg.text}</p>
      ))}
    </div>
  )
}

🧠 Test Your Knowledge

What database does Supabase use?