Back to blogs

Supabase Server vs. Browser Client: Best Use Cases in Next.js

March 29, 2025
5 min read
Supabase Server vs. Browser Client: Best Use Cases in Next.js

Introduction


When integrating Supabase with a Next.js App Router project, developers often wonder whether to use the Supabase server client or the Supabase browser client. Choosing the right client is essential for ensuring secure and efficient communication between your Next.js app and Supabase. This blog will guide you through when and how to use the server and browser clients effectively, with practical examples.


What is Supabase?


Supabase is a backend-as-a-service (BaaS) that provides features like authentication, databases, and storage. It is a popular alternative to Firebase and offers support for RESTful APIs, WebSockets, and real-time capabilities.


Supabase Server vs. Browser Client: Key Differences


Supabase Server Client


  1. Use Case: Ideal for secure operations, like server-side rendering (SSR), API routes, and backend operations.
  2. Security: Protects your Supabase API keys and prevents exposure to unauthorized users.
  3. Performance: Reduces latency by performing data fetching on the server, ensuring faster page loads.
  4. Where to Use:Server-side rendered pages (SSR)
  5. API routes (e.g., /api/*)
  6. Edge functions or middleware


Supabase Browser Client


  1. Use Case: Suitable for client-side operations where data fetching or updates need to happen after the page has loaded.
  2. Security: Exposes a public API key, which is safe to use in the browser.
  3. Performance: May result in slower page loads if used for fetching large data sets.
  4. Where to Use:Client-side components
  5. Static pages that require client-side interactivity
  6. Authentication and user session management


How to Use Supabase Server and Browser Client in Next.js App Router


1. Setting Up Supabase in Your Project


# Install Supabase JS
npm install @supabase/supabase-js


2. Creating a Supabase Client


Server Client Configuration


Create a file lib/supabase-server.js:

// lib/supabase-server.js
import { createServerClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';

export function createSupabaseServerClient() {
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.SUPABASE_SERVICE_ROLE_KEY,
{ cookies }
);
}


Browser Client Configuration


Create a file lib/supabase-browser.js:

// lib/supabase-browser.js
import { createBrowserClient } from '@supabase/auth-helpers-nextjs';

export function createSupabaseBrowserClient() {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
);
}


3. When to Use Supabase Server Client


a) Server-Side Rendering (SSR)

Use the server client when fetching data during server-side rendering to improve SEO and page performance.


// app/posts/[id]/page.js
import { createSupabaseServerClient } from '@/lib/supabase-server';

export async function generateStaticParams() {
const supabase = createSupabaseServerClient();
const { data: posts } = await supabase.from('posts').select('id');

return posts.map((post) => ({ id: post.id.toString() }));
}

export default async function PostPage({ params }) {
const supabase = createSupabaseServerClient();
const { data: post } = await supabase
.from('posts')
.select('*')
.eq('id', params.id)
.single();

if (!post) {
notFound();
}

return <div>{post.title}</div>;
}


b) API Routes


When creating API endpoints that interact with Supabase, always use the server client to avoid exposing sensitive keys.


// app/api/posts/route.js
import { createSupabaseServerClient } from '@/lib/supabase-server';

export async function POST(req) {
const supabase = createSupabaseServerClient();
const { title, content } = await req.json();

const { data, error } = await supabase.from('posts').insert([{ title, content }]);

if (error) {
return new Response(JSON.stringify({ error: error.message }), { status: 500 });
}

return new Response(JSON.stringify({ data }), { status: 200 });
}


4. When to Use Supabase Browser Client


a) Client-Side Authentication


Use the browser client for user sign-in, sign-up, and managing sessions on the client side.


// app/login/page.js
'use client';
import { createSupabaseBrowserClient } from '@/lib/supabase-browser';

export default function LoginPage() {
const supabase = createSupabaseBrowserClient();

async function handleLogin(email, password) {
const { data, error } = await supabase.auth.signInWithPassword({ email, password });
if (error) {
console.error('Login error:', error);
} else {
console.log('Logged in successfully:', data);
}
}

return <button onClick={() => handleLogin('test@email.com', 'password')}>Login</button>;
}


b) Client-Side Data Fetching


If you need to fetch or modify data after the page loads, use the browser client.


// app/dashboard/page.js
'use client';
import { createSupabaseBrowserClient } from '@/lib/supabase-browser';
import { useEffect, useState } from 'react';

export default function Dashboard() {
const [posts, setPosts] = useState([]);
const supabase = createSupabaseBrowserClient();

useEffect(() => {
async function fetchPosts() {
const { data, error } = await supabase.from('posts').select('*');
if (data) setPosts(data);
}
fetchPosts();
}, []);

return (
<div>
<h1>Dashboard</h1>
{posts.map((post) => (
<div key={post.id}>{post.title}</div>
))}
</div>
);
}


Security Considerations


  1. Never use the Supabase service role key in the browser to avoid security risks.
  2. Always handle sensitive data and authentication logic on the server side using the server client.


SEO Optimization Tips


  1. Use SSR when fetching dynamic content to improve search engine rankings.
  2. Implement appropriate meta tags and headers to optimize the performance of your Next.js pages.


Conclusion


In a Next.js App Router project, choosing between Supabase's server client and browser client depends on your use case. Use the server client for SSR, API routes, and sensitive operations, while the browser client is ideal for client-side interactions and authentication. By understanding these differences, you can build secure and performant applications that leverage Supabase effectively.

supabasesupabase next jssupabase clientsupabase serversupabase browsersupabase ssrhow to use supabase with next jssupabase browser vs server clientsupabase server side auth in next jsnext js with supabase api usage