Logo di Add Supabase Auth

Add Supabase Auth

Community
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

Panoramica

Pubblicato dakhadinakbarlabs
Repositoryexpo-mobile-app-builder
Nome della skilladd-supabase-auth
Stelle
3
Fork
0
File inclusi
1
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • File inclusi: 1

    Script, template e riferimenti che il modello può leggere mentre lavora. I file sono di sola lettura e non vengono mai eseguiti.

  • Open source

    Pubblicata da khadinakbarlabs su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Add Supabase Auth in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/khadinakbarlabs/expo-mobile-app-builder/tree/main/skills/add-supabase-auth
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Aggiungi skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella della skill nella directory delle skill di quell'agente.

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
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Add Supabase Auth in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Add Supabase Auth non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Add Supabase Auth non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

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.

File inclusi

Il modello legge questi file quando servono, mentre la skill è caricata. Sono accessibili in sola lettura e non vengono mai eseguiti.

Domande frequenti

Cosa fa la skill IA 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'.

Perché usare Add Supabase Auth su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Add Supabase Auth è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che la skill smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Add Supabase Auth in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/khadinakbarlabs/expo-mobile-app-builder/tree/main/skills/add-supabase-auth. TypingMind legge il file SKILL.md, include i file associati e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Add Supabase Auth?

Qualsiasi modello che colleghi a TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Add Supabase Auth?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Add Supabase Auth: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Add Supabase Auth è gratuita?

Sì. È pubblicata su GitHub da khadinakbarlabs con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, template o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Elenco completo

Crea subito il tuo spazio di lavoro AI

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇