การตั้งค่าไคลเอนต์ Supabase ใน React Native
สร้างโปรเจกต์ Supabase ติดตั้ง @supabase/supabase-js เริ่มต้นไคลเอนต์ด้วย URL โปรเจกต์และคีย์นิรนาม แล้วกำหนดให้ AsyncStorage เป็นที่จัดเก็บเซสชัน
การตั้งค่าไคลเอนต์ Supabase ใน React Native เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What Is Supabase?
Supabase is an open-source Firebase alternative that provides a hosted PostgreSQL database, authentication, real-time subscriptions, and file storage — all accessible through a simple JavaScript client. It is an excellent backend choice for React Native apps because it requires no server code for common operations.
Unlike Firebase, Supabase uses standard SQL and lets you query your data with full relational power. You create a project on supabase.com and get a project URL and an anon key that you use in your app.
Installing the Supabase JS Client
To use Supabase in a React Native project, install the official JavaScript client along with the AsyncStorage adapter that Supabase uses to persist auth sessions on mobile devices.
Run the following command in your project root. The @supabase/supabase-js package handles all API communication, while @react-native-async-storage/async-storage stores the session token between app launches.
npx expo install @supabase/supabase-js @react-native-async-storage/async-storageCreating a Supabase Client Instance
You initialize the Supabase client once and export it for use throughout the app. Create a file called lib/supabase.ts and call createClient with your project URL and anon key.
The auth options tell the client to use AsyncStorage so the session persists after the app is closed, and detectSessionInUrl is set to false because React Native does not use browser URLs for OAuth callbacks.
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createClient } from '@supabase/supabase-js';
const SUPABASE_URL = 'https://your-project.supabase.co';
const SUPABASE_ANON_KEY = 'your-anon-key';
export const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
auth: {
storage: AsyncStorage,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: false,
},
});Where to Store Your Supabase Keys
Your Supabase URL and anon key are not secret — the anon key is meant to be used in client-side code and is protected by Row Level Security (RLS) policies in your database. However, your service_role key is secret and must never be embedded in a mobile app.
A best practice is to store the public keys in environment variables using a .env file and access them via process.env.EXPO_PUBLIC_SUPABASE_URL. Expo automatically exposes variables prefixed with EXPO_PUBLIC_ to the JavaScript bundle.
# .env
EXPO_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
EXPO_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
# lib/supabase.ts
const SUPABASE_URL = process.env.EXPO_PUBLIC_SUPABASE_URL!;
const SUPABASE_ANON_KEY = process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY!;Understanding Row Level Security
Row Level Security (RLS) is the cornerstone of Supabase security. When RLS is enabled on a table, every query from the anon or authenticated key is filtered through policies you define in SQL. Without RLS, anyone with your anon key can read or modify all rows.
A typical policy allows users to read only their own rows: USING (auth.uid() = user_id). You enable RLS in the Supabase dashboard under the Authentication > Policies section, or with SQL: ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
-- Enable RLS on a table
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
-- Allow users to read only their own posts
CREATE POLICY 'Users read own posts'
ON posts FOR SELECT
USING (auth.uid() = user_id);
-- Allow users to insert posts for themselves
CREATE POLICY 'Users insert own posts'
ON posts FOR INSERT
WITH CHECK (auth.uid() = user_id);Verifying the Client Setup
After creating the client, you can verify it is configured correctly by performing a simple health check query. Calling supabase.from('your_table').select('count') will return an error if the URL or key is wrong, or a result if the connection is successful.
A common pattern is to test the connection in a useEffect during development and log any errors. Remember to remove debug logging before publishing to production.
import { useEffect } from 'react';
import { supabase } from '../lib/supabase';
export default function App() {
useEffect(() => {
async function testConnection() {
const { data, error } = await supabase.from('profiles').select('count');
if (error) {
console.error('Supabase connection error:', error.message);
} else {
console.log('Connected to Supabase:', data);
}
}
testConnection();
}, []);
return null;
}Auth Session Persistence with AsyncStorage
By setting storage: AsyncStorage in the Supabase client options, the auth session (JWT token and refresh token) is automatically saved to device storage. When the user reopens the app, the client reads this stored session and restores the authenticated state without requiring them to log in again.
You can listen to auth state changes with supabase.auth.onAuthStateChange, which fires whenever the session is created, refreshed, or destroyed. This is useful for driving your navigation stack.
import { useEffect, useState } from 'react';
import { Session } from '@supabase/supabase-js';
import { supabase } from '../lib/supabase';
export function useSession() {
const [session, setSession] = useState<Session | null>(null);
useEffect(() => {
supabase.auth.getSession().then(({ data: { session } }) => {
setSession(session);
});
const { data: { subscription } } = supabase.auth.onAuthStateChange(
(_event, session) => setSession(session)
);
return () => subscription.unsubscribe();
}, []);
return session;
}Supabase Project Dashboard Overview
The Supabase dashboard at app.supabase.com gives you a full view of your backend. Key sections include:
- Table Editor — create and browse database tables visually
- Auth — manage users, configure providers, and set policies
- Storage — manage file buckets for images and documents
- API — view auto-generated REST and real-time API documentation
The SQL Editor lets you run arbitrary SQL queries against your database, which is useful for creating tables, indexes, and RLS policies during development.
Creating a Profiles Table
A common pattern in Supabase apps is to create a profiles table that extends the built-in auth.users table with app-specific data like display names and avatars. You can use a database trigger to automatically create a profile row when a new user signs up.
The id column references auth.users, so each profile is linked to exactly one authenticated user. RLS policies ensure users can only read and update their own profile.
-- profiles table
CREATE TABLE profiles (
id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
username TEXT UNIQUE,
avatar_url TEXT,
created_at TIMESTAMPTZ DEFAULT now()
);
ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;
CREATE POLICY 'Public profiles are viewable'
ON profiles FOR SELECT USING (true);
CREATE POLICY 'Users update own profile'
ON profiles FOR UPDATE USING (auth.uid() = id);Auto-Refresh Token Behavior
Supabase JWTs expire after one hour by default. When you set autoRefreshToken: true in the client options, the client automatically calls the refresh endpoint before the token expires, keeping the user logged in without any intervention from your code.
If the refresh fails (for example, the user's internet is offline for an extended period), the client emits a TOKEN_REFRESHED event followed by a SIGNED_OUT event. You should handle SIGNED_OUT in your onAuthStateChange listener to redirect the user back to the login screen.
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_OUT') {
// Navigate user to login screen
navigation.reset({
index: 0,
routes: [{ name: 'Login' }],
});
}
if (event === 'TOKEN_REFRESHED') {
console.log('Token refreshed successfully');
}
});TypeScript Types from Supabase
Supabase can generate TypeScript types from your database schema using the Supabase CLI. Run npx supabase gen types typescript to produce a database.types.ts file. You then pass this as a generic to createClient for fully typed database queries.
Typed queries catch field-name typos at compile time and give you auto-complete in your editor — a significant productivity boost on larger projects.
import { Database } from './database.types';
import { createClient } from '@supabase/supabase-js';
export const supabase = createClient<Database>(
process.env.EXPO_PUBLIC_SUPABASE_URL!,
process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY!
);
// Now queries are fully typed:
// supabase.from('profiles').select('id, username')
// TypeScript knows the shape of each rowQuick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: how to install and initialize the Supabase JS client, the role of AsyncStorage in persisting auth sessions, and why Row Level Security is essential when using the anon key in mobile apps. Next up we explore authentication flows with Supabase including email/password and OAuth providers.
คำถามที่พบบ่อย
บทเรียน “การตั้งค่าไคลเอนต์ Supabase ใน React Native” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การตั้งค่าไคลเอนต์ Supabase ใน React Native” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การตั้งค่าไคลเอนต์ Supabase ใน React Native”
สร้างโปรเจกต์ Supabase ติดตั้ง @supabase/supabase-js เริ่มต้นไคลเอนต์ด้วย URL โปรเจกต์และคีย์นิรนาม แล้วกำหนดให้ AsyncStorage เป็นที่จัดเก็บเซสชัน คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การตั้งค่าไคลเอนต์ Supabase ใน React Native” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม
ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การตั้งค่าไคลเอนต์ Supabase ใน React Native
- การยืนยันตัวตนด้วยอีเมลและ OAuth
- การสืบค้นฐานข้อมูลด้วยไคลเอนต์ Supabase
- การสมัครรับข้อมูลแบบเรียลไทม์