Logo Add Supabase Auth

Add Supabase Auth

Cộng đồng
khadinakbarlabs
add-supabase-auth

Add Supabase Auth to a React Native + Expo app with Apple Sign In, email magic link, and session management. Use when the user says 'add supabase auth', 'apple sign in supabase', 'magic link rn', 'auth setup', 'supabase login'.

Add to TypingMind

Tổng quan

Nhà phát hànhkhadinakbarlabs
Kho mãexpo-mobile-app-builder
Tên kỹ năngadd-supabase-auth
Sao
3
Bản fork
0
Tệp đi kèm
1
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 1 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được khadinakbarlabs công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Add Supabase Auth trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/khadinakbarlabs/expo-mobile-app-builder/tree/main/skills/add-supabase-auth
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/khadinakbarlabs/expo-mobile-app-builder.git /tmp/expo-mobile-app-builder
mkdir -p .claude/skills
cp -r /tmp/expo-mobile-app-builder/skills/add-supabase-auth .claude/skills/add-supabase-auth
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Add Supabase Auth trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Add Supabase Auth ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Add Supabase Auth với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Add Supabase Auth to RN + Expo

Use app-owned public project configuration, persistent sessions and validated magic-link callbacks. These examples belong to the consuming app; the installed plugin has no authentication service or credential reader. Preserve an existing app's auth provider and navigation unless migration is explicitly requested.

Install

In the consuming Expo app, after dependency changes are authorized:

bash
pnpm add @supabase/supabase-js react-native-url-polyfill
npm exec --no -- expo install @react-native-async-storage/async-storage expo-apple-authentication expo-linking

Explicit public client configuration

Obtain the intended app's Project URL and publishable key from its owner. Create lib/public-config.ts exporting publicSupabaseConfig with url and publishableKey. These are public app configuration, not plugin configuration. Do not discover values from the installer's environment, local credentials or unrelated projects. Never place a secret or service-role key in the mobile bundle; use Row Level Security for every exposed table. Existing legacy anon-key projects should follow Supabase's migration guidance before using this publishable-key example.

lib/supabase.ts:

ts
import 'react-native-url-polyfill/auto';
import { Platform } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createClient } from '@supabase/supabase-js';
import { publicSupabaseConfig } from './public-config';

function createAppSupabase(config: { url: string; publishableKey: string }) {
  const url = new URL(config.url);
  if (url.protocol !== 'https:' || url.username || url.password ||
      url.search || url.hash || url.pathname !== '/' ||
      !config.publishableKey.startsWith('sb_publishable_')) {
    throw new Error('Provide the intended app public Supabase configuration.');
  }
  return createClient(url.origin, config.publishableKey, {
    auth: {
      ...(Platform.OS !== 'web' ? { storage: AsyncStorage } : {}),
      autoRefreshToken: true,
      persistSession: true,
      detectSessionInUrl: false,
      flowType: 'pkce',
    },
  });
}

export const supabase = createAppSupabase(publicSupabaseConfig);

Native session storage contains this app's signed-in user session. AsyncStorage is unencrypted; choose a platform-supported protected storage adapter when the app's threat model requires it. No app session, key or callback URL belongs in logs or analytics.

Magic link and callback

Register the app's chosen scheme and exact redirect in the Supabase Auth redirect allowlist. The example below uses yourapp://auth/callback; replace it consistently. Rebuild the development binary after scheme changes and test on both iOS and Android.

json
{
  "expo": {
    "scheme": "yourapp",
    "ios": { "usesAppleSignIn": true },
    "plugins": ["expo-apple-authentication"]
  }
}
ts
export const AUTH_REDIRECT = 'yourapp://auth/callback';

export async function sendMagicLink(email: string) {
  const { error } = await supabase.auth.signInWithOtp({
    email,
    options: { emailRedirectTo: AUTH_REDIRECT },
  });
  if (error) throw new Error('Could not send the sign-in link. Please try again.');
}

The PKCE client persists its verifier before sending the link. Open the link on the same device/app that initiated sign-in. Expired, reused or cross-device links need a fresh request; disable overlapping sign-in requests. Do not mix implicit token-fragment callbacks with this PKCE example.

Copy this handler into the app. It checks the exact destination before passing a one-time code to the configured Supabase client, rejects ambiguous/error payloads, deduplicates warm/cold deliveries and exposes generic errors.

js
// lib/auth-callback.js
export function createAuthCallbackHandler(client, redirectTo) {
  const expected = new URL(redirectTo);
  let lastCode = null;
  let lastResult = null;
  const failed = () => new Error('Sign-in could not be completed. Request a new link.');
  return async function handleAuthCallback(rawUrl) {
    let url;
    try { url = new URL(rawUrl); } catch { return 'ignored'; }
    if (url.protocol !== expected.protocol || url.hostname !== expected.hostname ||
        url.port !== expected.port || url.pathname !== expected.pathname ||
        url.username || url.password) return 'ignored';
    const codes = url.searchParams.getAll('code');
    if (url.hash || url.searchParams.has('error') || url.searchParams.has('error_code') ||
        codes.length !== 1 || !codes[0].trim() || codes[0].length > 4096) throw failed();
    const code = codes[0];
    if (code === lastCode && lastResult) return lastResult;
    lastCode = code;
    lastResult = Promise.resolve().then(async () => {
      const { data, error } = await client.auth.exchangeCodeForSession(code);
      if (error || !data?.session) throw failed();
      return 'signed-in';
    }).catch(() => {
      if (lastCode === code) { lastCode = null; lastResult = null; }
      throw failed();
    });
    return lastResult;
  };
}

Register once in the root layout. Keep an app/auth/callback.tsx route accessible while signed out so Expo Router can resolve the link before the protected app group opens. Its screen should show a waiting state and generic retry action, never render URL parameters.

tsx
import { useEffect } from 'react';
import { Alert } from 'react-native';
import * as Linking from 'expo-linking';
import { supabase } from '@/lib/supabase';
import { AUTH_REDIRECT } from '@/lib/auth-redirect';
import { createAuthCallbackHandler } from '@/lib/auth-callback';

// Export AUTH_REDIRECT from lib/auth-redirect.ts and import it in sendMagicLink too.
const handleAuthCallback = createAuthCallbackHandler(supabase, AUTH_REDIRECT);

export function useAuthLinks() {
  useEffect(() => {
    let mounted = true;
    const receive = async (url: string) => {
      if (!mounted) return;
      try { await handleAuthCallback(url); }
      catch { if (mounted) Alert.alert('Sign-in failed', 'Request a new link and open it in this app.'); }
    };
    const sub = Linking.addEventListener('url', ({ url }) => { void receive(url); });
    void Linking.getInitialURL().then(url => { if (url) void receive(url); })
      .catch(() => { if (mounted) Alert.alert('Sign-in failed', 'Please reopen the sign-in link.'); });
    return () => { mounted = false; sub.remove(); };
  }, []);
}

Session and protected routes (SDK 54)

Call the session hook once at the layout/provider boundary. Subscribe before loading stored state so a completed callback cannot be overwritten by an older session read.

tsx
import { useEffect, useState } from 'react';
import { AppState, Platform } from 'react-native';
import type { Session } from '@supabase/supabase-js';
import { supabase } from '@/lib/supabase';

export function useSession() {
  const [session, setSession] = useState<Session | null>(null);
  const [loading, setLoading] = useState(true);
  const [failed, setFailed] = useState(false);
  useEffect(() => {
    let mounted = true;
    let observedAuth = false;
    const { data: { subscription } } = supabase.auth.onAuthStateChange((_, next) => {
      observedAuth = true;
      if (mounted) { setSession(next); setLoading(false); setFailed(false); }
    });
    void supabase.auth.getSession().then(({ data, error }) => {
      if (!mounted || observedAuth) return;
      setSession(error ? null : data.session); setFailed(Boolean(error)); setLoading(false);
    }).catch(() => { if (mounted && !observedAuth) { setFailed(true); setLoading(false); } });
    const refresh = (state: string) => {
      if (state === 'active') supabase.auth.startAutoRefresh();
      else supabase.auth.stopAutoRefresh();
    };
    const listener = Platform.OS !== 'web' ? AppState.addEventListener('change', refresh) : null;
    if (Platform.OS !== 'web') refresh(AppState.currentState);
    return () => {
      mounted = false; subscription.unsubscribe(); listener?.remove();
      if (Platform.OS !== 'web') supabase.auth.stopAutoRefresh();
    };
  }, []);
  return { session, loading, failed };
}

In the root layout use Expo Router's Stack.Protected, not conditional Stack.Screen declarations. Put the callback inside the signed-out guard: successful authentication removes its waiting screen and opens the app group, including when an already signed-in user opens a callback link. Keep (auth) first so signed-out fallback opens login instead of the waiting callback. This protects navigation only; enforce server authorization and database RLS independently.

tsx
import { Stack } from 'expo-router';
import { ActivityIndicator, Text } from 'react-native';
import { useSession } from '@/hooks/useSession';
import { useAuthLinks } from '@/hooks/useAuthLinks';

export default function RootLayout() {
  useAuthLinks();
  const { session, loading, failed } = useSession();
  if (loading) return <ActivityIndicator accessibilityLabel="Loading account" />;
  if (failed) return <Text>Account could not load. Reopen the app to retry.</Text>;
  return <Stack>
    <Stack.Protected guard={!session}>
      <Stack.Screen name="(auth)" />
      <Stack.Screen name="auth/callback" />
    </Stack.Protected>
    <Stack.Protected guard={Boolean(session)}><Stack.Screen name="(app)" /></Stack.Protected>
  </Stack>;
}

Apple sign-in and platform parity

Native expo-apple-authentication is iOS-only. Check AppleAuthentication.isAvailableAsync() before rendering its button; give it explicit width and height. On press, call signInAsync, require a non-empty identityToken, and pass it to supabase.auth.signInWithIdToken({ provider: 'apple', token: credential.identityToken }). Treat ERR_REQUEST_CANCELED as cancellation; show a generic retry message for other errors. Never log provider credentials. Configure the iOS bundle ID and capability with the app owner. Android retains the same magic-link/session flow; an Apple browser OAuth option needs a separately configured Services ID and browser callback flow.

Use the current Apple 4.8 guideline to determine whether an equivalent login option is required; exceptions exist. Do not assume every social-login app has identical obligations. Store Apple's name/email only when provided and consented; relay email is valid. Verify Apple sign-in on a real supported device.

Verification and references

Pair with choose-backend, account-deletion-flow, and 5-1-2-i-ai-disclosure where applicable.

Tệp đi kèm

Khi kỹ năng đã được tải, mô hình có thể đọc các tệp này nếu cần. Các tệp này chỉ dùng để đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Add Supabase Auth làm được gì?

Add Supabase Auth to a React Native + Expo app with Apple Sign In, email magic link, and session management. Use when the user says 'add supabase auth', 'apple sign in supabase', 'magic link rn', 'auth setup', 'supabase login'.

Vì sao nên dùng Add Supabase Auth trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Add Supabase Auth là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Add Supabase Auth trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/khadinakbarlabs/expo-mobile-app-builder/tree/main/skills/add-supabase-auth. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm rồi cài đặt cả gói dưới dạng một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Add Supabase Auth?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Add Supabase Auth với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Add Supabase Auth với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Add Supabase Auth có miễn phí không?

Có. Kỹ năng này được khadinakbarlabs phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇