0
0
NextjsHow-ToBeginner · 4 min read

How to Use Supabase with Next.js: Simple Setup and Example

To use Supabase with Next.js, install the @supabase/supabase-js client, create a Supabase client instance with your project URL and anon key, then use it inside your React components or API routes to fetch or modify data. Initialize the client in a separate file and import it where needed for clean code.
📐

Syntax

First, install the Supabase client library. Then create a client instance with your Supabase URL and anon key. Use this client to call Supabase methods like from() to access tables and select() to fetch data.

Example parts:

  • createClient(supabaseUrl, supabaseAnonKey): Initializes the Supabase client.
  • supabase.from('table').select(): Queries data from a table.
javascript
import { createClient } from '@supabase/supabase-js'

const supabaseUrl = 'https://your-project.supabase.co'
const supabaseAnonKey = 'your-anon-key'

export const supabase = createClient(supabaseUrl, supabaseAnonKey)
💻

Example

This example shows how to fetch and display a list of users from a Supabase table called profiles inside a Next.js functional component using React hooks.

javascript
import { useEffect, useState } from 'react'
import { supabase } from '../lib/supabaseClient'

export default function Profiles() {
  const [profiles, setProfiles] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function fetchProfiles() {
      const { data, error } = await supabase.from('profiles').select('*')
      if (error) {
        console.error('Error fetching profiles:', error)
      } else {
        setProfiles(data)
      }
      setLoading(false)
    }
    fetchProfiles()
  }, [])

  if (loading) return <p>Loading profiles...</p>

  return (
    <ul>
      {profiles.map(profile => (
        <li key={profile.id}>{profile.username}</li>
      ))}
    </ul>
  )
}
Output
<ul><li>alice</li><li>bob</li><li>carol</li></ul>
⚠️

Common Pitfalls

Common mistakes when using Supabase with Next.js include:

  • Not securing your anon key properly (keep it in environment variables).
  • Calling Supabase client creation inside components instead of a separate module, causing multiple instances.
  • Not handling async data fetching properly, leading to empty or error states.
  • Forgetting to enable CORS or configure Supabase policies for your app.
javascript
/* Wrong: Creating client inside component causes multiple instances */
import { createClient } from '@supabase/supabase-js'

export default function Page() {
  const supabase = createClient('url', 'anon_key') // Bad practice
  // ...
}

/* Right: Create client once in a separate file and import */
// lib/supabaseClient.js
import { createClient } from '@supabase/supabase-js'
export const supabase = createClient('url', 'anon_key')

// In component
import { supabase } from '../lib/supabaseClient'

export default function Page() {
  // use supabase here
}
📊

Quick Reference

Summary tips for using Supabase with Next.js:

  • Install with npm install @supabase/supabase-js.
  • Store your Supabase URL and anon key in .env.local and access via process.env.
  • Create a single Supabase client instance in a separate file.
  • Use React hooks like useEffect for data fetching.
  • Handle loading and error states gracefully.

Key Takeaways

Create a single Supabase client instance outside components for reuse.
Use environment variables to keep your Supabase keys secure.
Fetch data asynchronously with React hooks like useEffect and handle loading states.
Always check for errors when querying Supabase and handle them gracefully.
Keep your Supabase URL and anon key private and never expose them in client-side code directly.