Skip to content

Cap-go/capacitor-supabase

@capgo/capacitor-supabase

Native Supabase SDK integration for Capacitor - Auth, Database, and JWT access.

This plugin provides native iOS and Android Supabase SDK functionality with the ability to retrieve JWT tokens for use in JavaScript/web layers.

Install

npm install @capgo/capacitor-supabase
npx cap sync

iOS Setup

No additional setup required. The plugin uses Swift Package Manager to include the Supabase Swift SDK.

Android Setup

The plugin requires a minimum SDK of 26 (Android 8.0). Make sure your android/variables.gradle has:

minSdkVersion = 26

Usage

Initialize the Client

import { CapacitorSupabase } from '@capgo/capacitor-supabase';

await CapacitorSupabase.initialize({
  supabaseUrl: 'https://your-project.supabase.co',
  supabaseKey: 'your-anon-key'
});

Authentication

Sign In with Email/Password

const { session, user } = await CapacitorSupabase.signInWithPassword({
  email: '[email protected]',
  password: 'password123'
});

// Access the JWT token
console.log('JWT:', session?.accessToken);

Sign Up

const { session, user } = await CapacitorSupabase.signUp({
  email: '[email protected]',
  password: 'password123',
  data: { name: 'John Doe' }
});

OAuth Sign In

await CapacitorSupabase.signInWithOAuth({
  provider: 'google',
  redirectTo: 'myapp://callback'
});

OTP Sign In

// Send OTP
await CapacitorSupabase.signInWithOtp({
  email: '[email protected]'
});

// Verify OTP
const { session, user } = await CapacitorSupabase.verifyOtp({
  email: '[email protected]',
  token: '123456',
  type: 'email'
});

Sign Out

await CapacitorSupabase.signOut();

Session Management

Get Current Session

const { session } = await CapacitorSupabase.getSession();
if (session) {
  console.log('JWT:', session.accessToken);
  console.log('Refresh Token:', session.refreshToken);
  console.log('Expires At:', session.expiresAt);
}

Refresh Session

const { session } = await CapacitorSupabase.refreshSession();

Get Current User

const { user } = await CapacitorSupabase.getUser();
if (user) {
  console.log('User ID:', user.id);
  console.log('Email:', user.email);
}

Set Session Manually

const { session } = await CapacitorSupabase.setSession({
  accessToken: 'eyJ...',
  refreshToken: 'abc123'
});

Listen to Auth State Changes

const listener = await CapacitorSupabase.addListener(
  'authStateChange',
  ({ event, session }) => {
    console.log('Auth event:', event);
    // Events: INITIAL_SESSION, SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED, USER_UPDATED
    if (session) {
      console.log('JWT:', session.accessToken);
    }
  }
);

// Later, remove the listener
listener.remove();

Using JWT with @supabase/supabase-js

The main use case is to get the JWT from native auth and use it with the JavaScript Supabase client:

import { createClient } from '@supabase/supabase-js';
import { CapacitorSupabase } from '@capgo/capacitor-supabase';

// Initialize native client
await CapacitorSupabase.initialize({
  supabaseUrl: 'https://your-project.supabase.co',
  supabaseKey: 'your-anon-key'
});

// Sign in natively
await CapacitorSupabase.signInWithPassword({
  email: '[email protected]',
  password: 'password'
});

// Get session with JWT
const { session } = await CapacitorSupabase.getSession();

// Create JS client with the native session
const supabase = createClient(
  'https://your-project.supabase.co',
  'your-anon-key',
  {
    global: {
      headers: {
        Authorization: `Bearer ${session?.accessToken}`
      }
    }
  }
);

// Now use supabase-js as normal
const { data } = await supabase.from('table').select('*');

Database Operations (Native)

The plugin also supports native database operations:

Select

const { data, error } = await CapacitorSupabase.select({
  table: 'users',
  columns: 'id, name, email',
  filter: { active: true },
  limit: 10,
  orderBy: 'created_at',
  ascending: false
});

Insert

const { data, error } = await CapacitorSupabase.insert({
  table: 'posts',
  values: { title: 'Hello', content: 'World' }
});

Update

const { data, error } = await CapacitorSupabase.update({
  table: 'posts',
  values: { title: 'Updated Title' },
  filter: { id: 1 }
});

Delete

const { data, error } = await CapacitorSupabase.delete({
  table: 'posts',
  filter: { id: 1 }
});

API

Capacitor Supabase Plugin for native Supabase SDK integration.

This plugin provides native iOS and Android Supabase SDK functionality with the ability to retrieve JWT tokens for use in JavaScript/web layers.

initialize(...)

initialize(options: SupabaseConfig) => Promise<void>

Initialize the Supabase client with your project credentials. Must be called before any other methods.

Param Type Description
options SupabaseConfig - Configuration options including URL and API key

Since: 0.0.1


signInWithPassword(...)

signInWithPassword(options: SignInWithPasswordOptions) => Promise<AuthResult>

Sign in with email and password.

Param Type Description
options SignInWithPasswordOptions - Email and password credentials

Returns: Promise<AuthResult>

Since: 0.0.1


signUp(...)

signUp(options: SignUpOptions) => Promise<AuthResult>

Sign up a new user with email and password.

Param Type Description
options SignUpOptions - Email, password, and optional user metadata

Returns: Promise<AuthResult>

Since: 0.0.1


signInWithOAuth(...)

signInWithOAuth(options: SignInWithOAuthOptions) => Promise<void>

Sign in with an OAuth provider. Opens the provider's authentication page.

Param Type Description
options SignInWithOAuthOptions - OAuth provider and optional redirect URL

Since: 0.0.1


signInWithOtp(...)

signInWithOtp(options: SignInWithOtpOptions) => Promise<void>

Sign in with OTP (One-Time Password) sent via email or SMS.

Param Type Description
options SignInWithOtpOptions - Email or phone number to send OTP to

Since: 0.0.1


verifyOtp(...)

verifyOtp(options: VerifyOtpOptions) => Promise<AuthResult>

Verify an OTP token.

Param Type Description
options VerifyOtpOptions - Email/phone, token, and verification type

Returns: Promise<AuthResult>

Since: 0.0.1


signOut()

signOut() => Promise<void>

Sign out the current user.

Since: 0.0.1


getSession()

getSession() => Promise<{ session: Session | null; }>

Get the current session if one exists. Returns the session with JWT access token.

Returns: Promise<{ session: Session | null; }>

Since: 0.0.1


refreshSession()

refreshSession() => Promise<{ session: Session | null; }>

Refresh the current session and get new tokens.

Returns: Promise<{ session: Session | null; }>

Since: 0.0.1


getUser()

getUser() => Promise<{ user: User | null; }>

Get the currently authenticated user.

Returns: Promise<{ user: User | null; }>

Since: 0.0.1


setSession(...)

setSession(options: SetSessionOptions) => Promise<{ session: Session | null; }>

Set the session manually with access and refresh tokens. Useful for restoring a session or integrating with external auth.

Param Type Description
options SetSessionOptions - Access and refresh tokens

Returns: Promise<{ session: Session | null; }>

Since: 0.0.1


addListener('authStateChange', ...)

addListener(eventName: 'authStateChange', listenerFunc: (data: AuthStateChange) => void) => Promise<PluginListenerHandle>

Listen to authentication state changes.

Param Type Description
eventName 'authStateChange' - Must be 'authStateChange'
listenerFunc (data: AuthStateChange) => void - Callback function for auth state changes

Returns: Promise<PluginListenerHandle>

Since: 0.0.1


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all listeners for auth state changes.

Since: 0.0.1


select(...)

select<T = unknown>(options: SelectOptions) => Promise<QueryResult<T[]>>

Execute a SELECT query on a table.

Param Type Description
options SelectOptions - Query options including table, columns, filters

Returns: Promise<QueryResult<T[]>>

Since: 0.0.1


insert(...)

insert<T = unknown>(options: InsertOptions) => Promise<QueryResult<T>>

Insert data into a table.

Param Type Description
options InsertOptions - Table name and values to insert

Returns: Promise<QueryResult<T>>

Since: 0.0.1


update(...)

update<T = unknown>(options: UpdateOptions) => Promise<QueryResult<T>>

Update data in a table.

Param Type Description
options UpdateOptions - Table name, values to update, and filter conditions

Returns: Promise<QueryResult<T>>

Since: 0.0.1


delete(...)

delete<T = unknown>(options: DeleteOptions) => Promise<QueryResult<T>>

Delete data from a table.

Param Type Description
options DeleteOptions - Table name and filter conditions

Returns: Promise<QueryResult<T>>

Since: 0.0.1


getPluginVersion()

getPluginVersion() => Promise<{ version: string; }>

Get the native Capacitor plugin version.

Returns: Promise<{ version: string; }>

Since: 0.0.1


Interfaces

SupabaseConfig

Configuration options for initializing the Supabase client.

Prop Type Description Since
supabaseUrl string The Supabase project URL. 0.0.1
supabaseKey string The Supabase anonymous/public key. 0.0.1

AuthResult

Result of authentication operations that return a session.

Prop Type Description Since
session Session | null The session if authentication was successful. 0.0.1
user User | null The authenticated user if successful. 0.0.1

Session

Session object containing authentication tokens.

Prop Type Description Since
accessToken string The JWT access token. Use this for authenticated API requests. 0.0.1
refreshToken string The refresh token for obtaining new access tokens. 0.0.1
tokenType string Token type (usually "bearer"). 0.0.1
expiresIn number Number of seconds until the access token expires. 0.0.1
expiresAt number Unix timestamp when the token expires. 0.0.1
user User The authenticated user. 0.0.1

User

User object returned from authentication operations.

Prop Type Description Since
id string Unique identifier for the user. 0.0.1
email string User's email address. 0.0.1
phone string User's phone number. 0.0.1
createdAt string Timestamp when the user was created. 0.0.1
lastSignInAt string Timestamp when the user last signed in. 0.0.1
userMetadata Record<string, unknown> User metadata (custom fields). 0.0.1
appMetadata Record<string, unknown> App metadata. 0.0.1

SignInWithPasswordOptions

Options for email/password sign-in.

Prop Type Description Since
email string User's email address. 0.0.1
password string User's password. 0.0.1

SignUpOptions

Options for email/password sign-up.

Prop Type Description Since
email string User's email address. 0.0.1
password string User's password. 0.0.1
data Record<string, unknown> Optional user metadata to store with the user. 0.0.1

SignInWithOAuthOptions

Options for OAuth sign-in.

Prop Type Description Since
provider OAuthProvider The OAuth provider to use. 0.0.1
redirectTo string URL to redirect to after authentication. 0.0.1
scopes string OAuth scopes to request. 0.0.1

SignInWithOtpOptions

Options for OTP sign-in.

Prop Type Description Since
email string User's email address (required if phone is not provided). 0.0.1
phone string User's phone number (required if email is not provided). 0.0.1

VerifyOtpOptions

Options for verifying OTP.

Prop Type Description Since
email string User's email address (required if phone is not provided). 0.0.1
phone string User's phone number (required if email is not provided). 0.0.1
token string The OTP token received via email/SMS. 0.0.1
type 'sms' | 'email' | 'magiclink' | 'signup' | 'recovery' The type of OTP verification. 0.0.1

SetSessionOptions

Options for setting a session manually.

Prop Type Description Since
accessToken string The access token. 0.0.1
refreshToken string The refresh token. 0.0.1

PluginListenerHandle

Prop Type
remove () => Promise<void>

AuthStateChange

Auth state change callback data.

Prop Type Description Since
event AuthChangeEvent The type of auth event. 0.0.1
session Session | null The current session (null if signed out). 0.0.1

QueryResult

Result of database queries.

Prop Type Description Since
data T | null The query result data. 0.0.1
error string | null Error message if the query failed. 0.0.1
count number Number of affected rows (for insert/update/delete). 0.0.1

SelectOptions

Options for database select queries.

Prop Type Description Since
table string The table name to query. 0.0.1
columns string Columns to select (default: "*"). 0.0.1
filter Record<string, unknown> Filter conditions as key-value pairs. 0.0.1
limit number Maximum number of rows to return. 0.0.1
offset number Number of rows to skip. 0.0.1
orderBy string Column to order by. 0.0.1
ascending boolean Order direction. 0.0.1
single boolean Return a single row instead of an array. 0.0.1

InsertOptions

Options for database insert queries.

Prop Type Description Since
table string The table name to insert into. 0.0.1
values Record<string, unknown> | Record<string, unknown>[] The data to insert (single object or array of objects). 0.0.1

UpdateOptions

Options for database update queries.

Prop Type Description Since
table string The table name to update. 0.0.1
values Record<string, unknown> The data to update. 0.0.1
filter Record<string, unknown> Filter conditions to match rows to update. 0.0.1

DeleteOptions

Options for database delete queries.

Prop Type Description Since
table string The table name to delete from. 0.0.1
filter Record<string, unknown> Filter conditions to match rows to delete. 0.0.1

Type Aliases

Record

Construct a type with a set of properties K of type T

{ [P in K]: T; }

OAuthProvider

Supported OAuth providers.

'apple' | 'azure' | 'bitbucket' | 'discord' | 'facebook' | 'figma' | 'github' | 'gitlab' | 'google' | 'kakao' | 'keycloak' | 'linkedin' | 'linkedin_oidc' | 'notion' | 'slack' | 'slack_oidc' | 'spotify' | 'twitch' | 'twitter' | 'workos' | 'zoom'

AuthChangeEvent

Auth state change event types.

'INITIAL_SESSION' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED' | 'USER_UPDATED' | 'PASSWORD_RECOVERY'

License

MPL-2.0

About

No description, website, or topics provided.

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Contributors 3

  •  
  •  
  •