Supabase + Next.js: The Standard Stack Toris Uses to Ship MVPs Fast
Practical Supabase + Next.js standards Toris applies to real products like MemeCatch, YM Guide, and LOVETRIP: PostgreSQL, auth, RLS, realtime, and storage.
Joohwan Yu · Founder, Full Stack Developer
Toris · Published
Contents
Q. Why does Toris use Supabase + Next.js as the standard stack? One @supabase/supabase-js client connects PostgreSQL, auth, realtime, and storage, and putting the security boundary in the database with RLS means you can ship a production-grade MVP in a few weeks without a separate backend.
🚀 Overview
Toris uses Supabase + Next.js as the standard stack for real products such as MemeCatch (밈캐치), YM Guide, and LOVETRIP. Supabase is an open-source alternative to Firebase that provides a PostgreSQL-based backend. You get a database, authentication, realtime subscriptions, and storage without running a backend server, so the cost of designing new infrastructure for every product disappears. For a one-person studio running several products in parallel, that saving is decisive.
This post collects the practical standards I settled on while building and operating those products. It walks through the setup I repeat every time I start a new product, in order: initial project setup, schema design, RLS, authentication, realtime features, storage, and deployment. It is not a tutorial. Think of it as the defaults we actually use.
Why we chose this combination
Strengths of Supabase:
- 🗄️ A powerful PostgreSQL-based database
- 🔐 Built-in authentication (including social login)
- 📡 Realtime subscriptions
- 🛡️ Row Level Security (RLS)
- 📁 File storage
- 🔧 Automatically generated REST/GraphQL APIs
Strengths of Next.js:
- ⚡ Excellent performance (SSR, SSG, ISR)
- 📱 Full-stack development (API Routes)
- 🎨 Support for modern React features
- 🚀 Easy deployment (Vercel)
🛠️ Project Setup
1. Create the Next.js project
npx create-next-app@latest my-supabase-app
cd my-supabase-app
2. Install the Supabase client
npm install @supabase/supabase-js
npm install @supabase/auth-helpers-nextjs
npm install @supabase/auth-helpers-react
npm install @supabase/auth-ui-react
npm install @supabase/auth-ui-shared
3. Set environment variables
Create a .env.local file:
NEXT_PUBLIC_SUPABASE_URL=your_supabase_project_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key
4. Configure the Supabase client
Create 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);
lib/supabase-server.js (for the server side):
import { createServerComponentClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
export const createServerSupabaseClient = () => {
return createServerComponentClient({ cookies });
};
🗄️ Database Design
Example: a blog application
I define the initial schema directly in the SQL editor of the Supabase dashboard. Taking a blog application as the example:
-- Profiles table
CREATE TABLE profiles (
id UUID PRIMARY KEY REFERENCES auth.users(id),
email TEXT,
full_name TEXT,
avatar_url TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Posts table
CREATE TABLE posts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title TEXT NOT NULL,
content TEXT,
excerpt TEXT,
slug TEXT UNIQUE NOT NULL,
published BOOLEAN DEFAULT FALSE,
author_id UUID REFERENCES profiles(id),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Comments table
CREATE TABLE comments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
content TEXT NOT NULL,
post_id UUID REFERENCES posts(id) ON DELETE CASCADE,
author_id UUID REFERENCES profiles(id),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Categories table
CREATE TABLE categories (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT UNIQUE NOT NULL,
description TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Post-category relationship table
CREATE TABLE post_categories (
post_id UUID REFERENCES posts(id) ON DELETE CASCADE,
category_id UUID REFERENCES categories(id) ON DELETE CASCADE,
PRIMARY KEY (post_id, category_id)
);
Setting up RLS (Row Level Security)
RLS is the core of security in this stack. Our default is to enforce access control through database policies rather than the API layer. When the client calls Supabase directly, that is the only boundary you can trust.
-- Enable RLS
ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
ALTER TABLE comments ENABLE ROW LEVEL SECURITY;
-- Profile policy
CREATE POLICY "Users can only modify their own profile" ON profiles
FOR ALL USING (auth.uid() = id);
-- Post policies
CREATE POLICY "Anyone can read posts" ON posts
FOR SELECT USING (published = true OR auth.uid() = author_id);
CREATE POLICY "Only the author can create or modify posts" ON posts
FOR ALL USING (auth.uid() = author_id);
-- Comment policies
CREATE POLICY "Anyone can read comments" ON comments
FOR SELECT USING (true);
CREATE POLICY "Only signed-in users can write comments" ON comments
FOR INSERT WITH CHECK (auth.uid() = author_id);
🔐 Implementing Authentication
1. Set up the auth context
contexts/AuthContext.js:
'use client';
import { createContext, useContext, useEffect, useState } from 'react';
import { supabase } from '@/lib/supabase';
const AuthContext = createContext({});
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within AuthProvider');
}
return context;
};
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const getSession = async () => {
const {
data: { session }
} = await supabase.auth.getSession();
setUser(session?.user ?? null);
setLoading(false);
};
getSession();
const {
data: { subscription }
} = supabase.auth.onAuthStateChange(async (event, session) => {
setUser(session?.user ?? null);
setLoading(false);
});
return () => subscription?.unsubscribe();
}, []);
const signUp = async (email, password, metadata = {}) => {
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
data: metadata
}
});
return { data, error };
};
const signIn = async (email, password) => {
const { data, error } = await supabase.auth.signInWithPassword({
email,
password
});
return { data, error };
};
const signOut = async () => {
const { error } = await supabase.auth.signOut();
return { error };
};
const value = {
user,
loading,
signUp,
signIn,
signOut
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
2. Login component
components/auth/LoginForm.jsx:
'use client';
import { useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { Auth } from '@supabase/auth-ui-react';
import { ThemeSupa } from '@supabase/auth-ui-shared';
import { supabase } from '@/lib/supabase';
export default function LoginForm() {
const { user } = useAuth();
if (user) {
return <div>You are already signed in.</div>;
}
return (
<div className="max-w-md mx-auto mt-8 p-6 bg-white rounded-lg shadow-md">
<Auth
supabaseClient={supabase}
appearance={{ theme: ThemeSupa }}
providers={['google', 'github']}
redirectTo={`${window.location.origin}/auth/callback`}
onlyThirdPartyProviders={false}
showLinks={true}
localization={{
variables: {
sign_in: {
email_label: 'Email',
password_label: 'Password',
button_label: 'Sign in',
loading_button_label: 'Signing in...',
link_text: 'Already have an account? Sign in'
},
sign_up: {
email_label: 'Email',
password_label: 'Password',
button_label: 'Sign up',
loading_button_label: 'Signing up...',
link_text: "Don't have an account? Sign up"
}
}
}}
/>
</div>
);
}
3. Handle the auth callback
app/auth/callback/route.js:
import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';
export async function GET(request) {
const requestUrl = new URL(request.url);
const code = requestUrl.searchParams.get('code');
if (code) {
const supabase = createRouteHandlerClient({ cookies });
await supabase.auth.exchangeCodeForSession(code);
}
return NextResponse.redirect(requestUrl.origin);
}
📊 Data CRUD Operations
1. Creating a post
components/posts/CreatePost.jsx:
'use client';
import { useState } from 'react';
import { supabase } from '@/lib/supabase';
import { useAuth } from '@/contexts/AuthContext';
export default function CreatePost() {
const { user } = useAuth();
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
if (!user) return;
setLoading(true);
const slug = title
.toLowerCase()
.replace(/ /g, '-')
.replace(/[^\w-]+/g, '');
const { data, error } = await supabase
.from('posts')
.insert([
{
title,
content,
slug,
author_id: user.id,
published: true
}
])
.select();
if (error) {
console.error('Error creating post:', error);
} else {
console.log('Post created:', data);
setTitle('');
setContent('');
}
setLoading(false);
};
if (!user) {
return <div>You need to sign in.</div>;
}
return (
<form onSubmit={handleSubmit} className="max-w-2xl mx-auto p-6">
<div className="mb-4">
<label className="block text-sm font-medium mb-2">Title</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500"
required
/>
</div>
<div className="mb-4">
<label className="block text-sm font-medium mb-2">Content</label>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
rows={10}
className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500"
required
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-blue-500 text-white py-3 rounded-lg hover:bg-blue-600 disabled:opacity-50"
>
{loading ? 'Publishing...' : 'Create post'}
</button>
</form>
);
}
2. Listing posts
components/posts/PostList.jsx:
'use client';
import { useState, useEffect } from 'react';
import { supabase } from '@/lib/supabase';
import Link from 'next/link';
export default function PostList() {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchPosts();
}, []);
const fetchPosts = async () => {
try {
const { data, error } = await supabase
.from('posts')
.select(
`
*,
profiles:author_id (
full_name,
avatar_url
)
`
)
.eq('published', true)
.order('created_at', { ascending: false });
if (error) throw error;
setPosts(data || []);
} catch (error) {
console.error('Error fetching posts:', error);
} finally {
setLoading(false);
}
};
if (loading) {
return <div className="text-center py-8">Loading...</div>;
}
return (
<div className="max-w-4xl mx-auto p-6">
<h1 className="text-3xl font-bold mb-8">Latest posts</h1>
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
{posts.map((post) => (
<article
key={post.id}
className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow"
>
<div className="p-6">
<h2 className="text-xl font-semibold mb-3">
<Link
href={`/posts/${post.slug}`}
className="text-gray-900 hover:text-blue-600"
>
{post.title}
</Link>
</h2>
{post.excerpt && (
<p className="text-gray-600 mb-4 line-clamp-3">
{post.excerpt}
</p>
)}
<div className="flex items-center justify-between text-sm text-gray-500">
<span>{post.profiles?.full_name || 'Anonymous'}</span>
<time dateTime={post.created_at}>
{new Date(post.created_at).toLocaleDateString('ko-KR')}
</time>
</div>
</div>
</article>
))}
</div>
</div>
);
}
📡 Implementing Realtime Features
A realtime comment system
components/comments/CommentSection.jsx:
'use client';
import { useState, useEffect } from 'react';
import { supabase } from '@/lib/supabase';
import { useAuth } from '@/contexts/AuthContext';
export default function CommentSection({ postId }) {
const { user } = useAuth();
const [comments, setComments] = useState([]);
const [newComment, setNewComment] = useState('');
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchComments();
// Set up the realtime subscription
const subscription = supabase
.channel(`comments:${postId}`)
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'comments',
filter: `post_id=eq.${postId}`
},
(payload) => {
if (payload.eventType === 'INSERT') {
setComments((prev) => [...prev, payload.new]);
} else if (payload.eventType === 'DELETE') {
setComments((prev) =>
prev.filter((comment) => comment.id !== payload.old.id)
);
}
}
)
.subscribe();
return () => {
supabase.removeChannel(subscription);
};
}, [postId]);
const fetchComments = async () => {
try {
const { data, error } = await supabase
.from('comments')
.select(
`
*,
profiles:author_id (
full_name,
avatar_url
)
`
)
.eq('post_id', postId)
.order('created_at', { ascending: true });
if (error) throw error;
setComments(data || []);
} catch (error) {
console.error('Error fetching comments:', error);
} finally {
setLoading(false);
}
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!user || !newComment.trim()) return;
try {
const { error } = await supabase.from('comments').insert([
{
content: newComment.trim(),
post_id: postId,
author_id: user.id
}
]);
if (error) throw error;
setNewComment('');
} catch (error) {
console.error('Error creating comment:', error);
}
};
return (
<div className="mt-8">
<h3 className="text-2xl font-bold mb-6">Comments ({comments.length})</h3>
{user && (
<form onSubmit={handleSubmit} className="mb-8">
<textarea
value={newComment}
onChange={(e) => setNewComment(e.target.value)}
placeholder="Write a comment..."
rows={3}
className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500"
/>
<button
type="submit"
disabled={!newComment.trim()}
className="mt-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50"
>
Post comment
</button>
</form>
)}
<div className="space-y-4">
{comments.map((comment) => (
<div key={comment.id} className="bg-gray-50 p-4 rounded-lg">
<div className="flex items-center mb-2">
<span className="font-medium">
{comment.profiles?.full_name || 'Anonymous'}
</span>
<time className="ml-2 text-sm text-gray-500">
{new Date(comment.created_at).toLocaleDateString('ko-KR')}
</time>
</div>
<p className="text-gray-700">{comment.content}</p>
</div>
))}
</div>
</div>
);
}
📁 File Upload (Storage)
Image upload component
components/upload/ImageUpload.jsx:
'use client';
import { useState } from 'react';
import { supabase } from '@/lib/supabase';
import { useAuth } from '@/contexts/AuthContext';
export default function ImageUpload({ onUpload }) {
const { user } = useAuth();
const [uploading, setUploading] = useState(false);
const uploadImage = async (event) => {
try {
setUploading(true);
if (!event.target.files || event.target.files.length === 0) {
throw new Error('Please select a file.');
}
const file = event.target.files[0];
const fileExt = file.name.split('.').pop();
const fileName = `${user.id}/${Date.now()}.${fileExt}`;
const { data, error } = await supabase.storage
.from('images')
.upload(fileName, file);
if (error) throw error;
// Get the public URL
const {
data: { publicUrl }
} = supabase.storage.from('images').getPublicUrl(fileName);
onUpload(publicUrl);
} catch (error) {
console.error('Error uploading image:', error);
alert(error.message);
} finally {
setUploading(false);
}
};
return (
<div>
<label className="block text-sm font-medium mb-2">Upload image</label>
<input
type="file"
accept="image/*"
onChange={uploadImage}
disabled={uploading}
className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
/>
{uploading && <p className="mt-2 text-sm text-gray-500">Uploading...</p>}
</div>
);
}
🔍 Advanced Features
1. Full-text search
// utils/search.js
export const searchPosts = async (query) => {
const { data, error } = await supabase
.from('posts')
.select(
`
*,
profiles:author_id (
full_name
)
`
)
.or(`title.ilike.%${query}%, content.ilike.%${query}%`)
.eq('published', true)
.order('created_at', { ascending: false });
return { data, error };
};
// Use PostgreSQL full-text search
export const fullTextSearch = async (query) => {
const { data, error } = await supabase.rpc('search_posts', {
search_query: query
});
return { data, error };
};
2. Pagination
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const POSTS_PER_PAGE = 10;
const loadMorePosts = async (page = 0) => {
setLoading(true);
const from = page * POSTS_PER_PAGE;
const to = from + POSTS_PER_PAGE - 1;
const { data, error } = await supabase
.from('posts')
.select('*')
.eq('published', true)
.order('created_at', { ascending: false })
.range(from, to);
if (data && data.length < POSTS_PER_PAGE) {
setHasMore(false);
}
if (page === 0) {
setPosts(data || []);
} else {
setPosts((prev) => [...prev, ...(data || [])]);
}
setLoading(false);
};
🚀 Deployment and Optimization
1. Deploy to Vercel
# Install the Vercel CLI
npm i -g vercel
# Deploy the project
vercel
# Set environment variables
vercel env add NEXT_PUBLIC_SUPABASE_URL
vercel env add NEXT_PUBLIC_SUPABASE_ANON_KEY
vercel env add SUPABASE_SERVICE_ROLE_KEY
2. Performance optimization
Database optimization:
-- Create indexes
CREATE INDEX posts_published_created_idx ON posts (published, created_at DESC);
CREATE INDEX comments_post_id_idx ON comments (post_id);
CREATE INDEX profiles_id_idx ON profiles (id);
Next.js optimization:
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
domains: ['your-supabase-project.supabase.co']
},
experimental: {
appDir: true
}
};
module.exports = nextConfig;
3. Hardening security
-- Tighten RLS policies
CREATE POLICY "Only the post author can update" ON posts
FOR UPDATE USING (auth.uid() = author_id);
CREATE POLICY "Only the comment author can delete" ON comments
FOR DELETE USING (auth.uid() = author_id);
-- Function security
CREATE OR REPLACE FUNCTION public.is_admin()
RETURNS BOOLEAN AS $$
BEGIN
RETURN EXISTS (
SELECT 1 FROM profiles
WHERE id = auth.uid() AND role = 'admin'
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
📚 References
Official docs
Topics to go deeper on
- Database Functions: writing PostgreSQL functions
- Edge Functions: Deno-based serverless functions
- Webhook: integrating with external services
- Multi-tenancy: separating data per tenant
- Performance Monitoring: monitoring query performance
Closing
Toris uses this setup as is in real products like MemeCatch (밈캐치), YM Guide, and LOVETRIP. If you want to ship an MVP in a few weeks with this stack, contact Toris. The way we work is laid out at toris.kr/process.
Advertisement