Nexentio Logo
Ana içeriğe geç
Blog'a Dön
BLOG

Supabase ile Full-Stack Uygulama Geliştirme: Backend Olmadan Modern Web Apps

13 dk okuma süresi
Supabase ile Full-Stack Uygulama Geliştirme: Backend Olmadan Modern Web Apps

SupabaseileFull-StackUygulamaGeliştirme:BackendOlmadanModernWebApps

Supabase ile PostgreSQL veritabanı, authentication, real-time subscriptions ve storage kullanarak tam özellikli full-stack uygulamalar geliştirme. Next.js entegrasyonu ve production best practices.

SupabaseFull-StackPostgreSQLBackendNext.js

Supabase, Firebase'in açık kaynak alternatifi olarak PostgreSQL tabanlı bir Backend-as-a-Service (BaaS) platformudur. Bu kapsamlı rehberde, Next.js projelerinizde Supabase kullanarak tam özellikli full-stack uygulamalar geliştirme tekniklerini ele alıyoruz.

Supabase Nedir?

Supabase, PostgreSQL veritabanı, authentication, real-time subscriptions, storage ve edge functions içeren açık kaynaklı bir platformdur. Firebase'in güçlü alternatifi olarak, geliştiricilere tam kontrol ve esneklik sunar.

Supabase'in temel özellikleri:

  • PostgreSQL Database: Güçlü, açık kaynak veritabanı
  • Authentication: Email, OAuth, Magic Link desteği
  • Real-time: WebSocket tabanlı real-time subscriptions
  • Storage: Dosya yükleme ve yönetimi
  • Edge Functions: Serverless function'lar
  • Row Level Security: Güvenli veri erişimi

Supabase Kurulumu

Supabase projesi oluşturma ve Next.js entegrasyonu:

# Supabase client kurulumu
npm install @supabase/supabase-js

# Next.js için helper functions
npm install @supabase/ssr

Supabase client oluşturma:

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

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;

export const supabase = createClient(supabaseUrl, supabaseAnonKey);

// Server-side client
// lib/supabase/server.ts
import { createServerClient } from '@supabase/ssr';
import { cookies } from 'next/headers';

export async function createClient() {
  const cookieStore = await cookies();
  
  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll();
        },
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options)
            );
          } catch {
            // Server component'te cookie set edilemez
          }
        },
      },
    }
  );
}

Veritabanı Yönetimi

Supabase, PostgreSQL veritabanı kullanır. Tablo oluşturma ve yönetim:

Supabase PostgreSQL veritabanı yönetimi
// SQL ile tablo oluşturma (Supabase SQL Editor)
CREATE TABLE posts (
  id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
  title TEXT NOT NULL,
  content TEXT,
  user_id UUID REFERENCES auth.users(id),
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

// Row Level Security (RLS) politikaları
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users can view own posts"
  ON posts FOR SELECT
  USING (auth.uid() = user_id);

CREATE POLICY "Users can insert own posts"
  ON posts FOR INSERT
  WITH CHECK (auth.uid() = user_id);

Next.js ile veri çekme:

// Server Component
import { createClient } from '@/lib/supabase/server';

export default async function PostsPage() {
  const supabase = await createClient();
  const { data: posts, error } = await supabase
    .from('posts')
    .select('*')
    .order('created_at', { ascending: false });
  
  if (error) {
    console.error(error);
    return <div>Error loading posts</div>;
  }
  
  return (
    <div>
      {posts?.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.content}</p>
        </article>
      ))}
    </div>
  );
}

// Client Component
'use client';
import { useEffect, useState } from 'react';
import { supabase } from '@/lib/supabase/client';

export default function PostsList() {
  const [posts, setPosts] = useState([]);
  
  useEffect(() => {
    async function fetchPosts() {
      const { data } = await supabase
        .from('posts')
        .select('*');
      setPosts(data || []);
    }
    fetchPosts();
  }, []);
  
  return (
    <div>
      {posts.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
        </article>
      ))}
    </div>
  );
}

Authentication

Supabase, güçlü authentication sistemi sunar:

// Email/Password ile kayıt
const { data, error } = await supabase.auth.signUp({
  email: 'user@example.com',
  password: 'secure-password',
});

// Email/Password ile giriş
const { data, error } = await supabase.auth.signInWithPassword({
  email: 'user@example.com',
  password: 'secure-password',
});

// OAuth ile giriş (Google, GitHub, etc.)
const { data, error } = await supabase.auth.signInWithOAuth({
  provider: 'google',
  options: {
    redirectTo: 'https://yourapp.com/auth/callback',
  },
});

// Magic Link (passwordless)
const { data, error } = await supabase.auth.signInWithOtp({
  email: 'user@example.com',
});

// Çıkış
await supabase.auth.signOut();

// Kullanıcı bilgilerini alma
const { data: { user } } = await supabase.auth.getUser();

Real-time Subscriptions

Supabase, WebSocket tabanlı real-time subscriptions sunar:

'use client';
import { useEffect } from 'react';
import { supabase } from '@/lib/supabase/client';

export default function RealtimePosts() {
  useEffect(() => {
    const channel = supabase
      .channel('posts-changes')
      .on(
        'postgres_changes',
        {
          event: '*', // INSERT, UPDATE, DELETE
          schema: 'public',
          table: 'posts',
        },
        (payload) => {
          console.log('Change received!', payload);
          // UI'ı güncelle
        }
      )
      .subscribe();

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

  return <div>Real-time posts will appear here</div>;
}

Storage (Dosya Yönetimi)

Supabase Storage, dosya yükleme ve yönetimi için kullanılır:

// Dosya yükleme
const { data, error } = await supabase.storage
  .from('avatars')
  .upload('user-123/avatar.jpg', file);

// Dosya indirme (public URL)
const { data } = supabase.storage
  .from('avatars')
  .getPublicUrl('user-123/avatar.jpg');

// Dosya silme
const { error } = await supabase.storage
  .from('avatars')
  .remove(['user-123/avatar.jpg']);

// Signed URL (private dosyalar için)
const { data } = await supabase.storage
  .from('private-files')
  .createSignedUrl('document.pdf', 3600); // 1 saat geçerli

Row Level Security (RLS)

RLS, veritabanı seviyesinde güvenlik sağlar:

// Tüm kullanıcılar okuyabilir
CREATE POLICY "Public posts are viewable by everyone"
  ON posts FOR SELECT
  USING (true);

// Sadece kendi postlarını güncelleyebilir
CREATE POLICY "Users can update own posts"
  ON posts FOR UPDATE
  USING (auth.uid() = user_id)
  WITH CHECK (auth.uid() = user_id);

// Admin tüm postları yönetebilir
CREATE POLICY "Admins can manage all posts"
  ON posts FOR ALL
  USING (
    EXISTS (
      SELECT 1 FROM profiles
      WHERE profiles.id = auth.uid()
      AND profiles.role = 'admin'
    )
  );

Next.js Entegrasyonu

Next.js projelerinde Supabase kullanımı için best practices:

  • Server Components: Veri çekme için server component'leri kullanın
  • Client Components: Real-time ve form işlemleri için client component'leri kullanın
  • Middleware: Authentication kontrolü için middleware kullanın
  • API Routes: Server-side işlemler için API route'ları kullanın
// middleware.ts
import { createServerClient } from '@supabase/ssr';
import { NextResponse, type NextRequest } from 'next/server';

export async function middleware(request: NextRequest) {
  let response = NextResponse.next({
    request: {
      headers: request.headers,
    },
  });

  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return request.cookies.getAll();
        },
        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value }) =>
            request.cookies.set(name, value)
          );
          response = NextResponse.next({
            request,
          });
          cookiesToSet.forEach(({ name, value, options }) =>
            response.cookies.set(name, value, options)
          );
        },
      },
    }
  );

  const {
    data: { user },
  } = await supabase.auth.getUser();

  // Protected route kontrolü
  if (!user && request.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  return response;
}

export const config = {
  matcher: [
    '/((?!_next/static|_next/image|favicon.ico|.*\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
  ],
};

Performans Optimizasyonu

Supabase kullanırken performans için:

  • Indexing: Sık sorgulanan kolonlara index ekleyin
  • Pagination: Büyük veri setleri için pagination kullanın
  • Caching: Next.js cache mekanizmalarını kullanın
  • Select Optimization: Sadece ihtiyaç duyulan kolonları seçin
  • Connection Pooling: Production'da connection pooling kullanın

Sonuç

Supabase, modern full-stack uygulamalar geliştirmek için güçlü bir platformdur. PostgreSQL veritabanı, authentication, real-time subscriptions ve storage özellikleri ile Next.js projelerinizde backend olmadan tam özellikli uygulamalar geliştirebilirsiniz. Bu rehberdeki teknikleri uygulayarak, production-ready full-stack uygulamalar oluşturabilirsiniz.

Backend otomasyonu için n8n rehberimizi, deployment için Vercel rehberimizi inceleyebilirsiniz.

Sık Sorulan Sorular

Supabase ücretsiz mi?

Evet, Supabase ücretsiz bir hobby plan sunar. Kişisel projeler için yeterlidir. Ticari projeler için ücretli planlar mevcuttur.

Supabase Firebase'ten farkı nedir?

Supabase PostgreSQL kullanır ve açık kaynaklıdır. Firebase NoSQL (Firestore) kullanır ve Google'ın sahip olduğu kapalı kaynak bir platformdur. Supabase daha fazla kontrol ve esneklik sunar.

Supabase self-hosted olarak kullanılabilir mi?

Evet, Supabase tamamen açık kaynaklıdır ve self-hosted olarak kullanılabilir. Docker ile kolayca kurulabilir.

Yazar Hakkında

Nexentio Ekibi

Full-Stack ve Backend Uzmanları

Supabase, PostgreSQL ve modern backend teknolojileri konusunda uzman ekibimiz, ölçeklenebilir full-stack uygulamalar geliştiriyor.

Daha fazla içerik keşfetmek için diğer blog yazılarımızı inceleyebilirsiniz.

Projenizi Geliştirmeye Hazır mısınız?

Next.js, SEO ve performans optimizasyonu konusunda uzman ekibimizle iletişime geçin.

Nexentio Instagram hesabı
WhatsApp ile iletişime geçin
Supabase ile Full-Stack Uygulama Geliştirme: Backend Olmadan Modern Web Apps | Nexentio | Nexentio