@capgo/capacitor-supabase

中文文档
8.2.7发布于 2026/10/15MPL-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 1.7万

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

原始使用文档
文档目录38 节
  1. ➡️ Get started for free
  2. Key features
  3. Why Capacitor Supabase?
  4. Documentation
  5. Compatibility
  6. Install
  7. iOS Setup
  8. Android Setup
  9. Usage
  10. Initialize the Client
  11. Authentication
  12. Session Management
  13. Listen to Auth State Changes
  14. Using JWT with @supabase/supabase-js
  15. Database Operations (Native)
  16. API
  17. initialize(...)
  18. signInWithPassword(...)
  19. signUp(...)
  20. signInAnonymously()
  21. signInWithOAuth(...)
  22. signInWithOtp(...)
  23. verifyOtp(...)
  24. signOut()
  25. getSession()
  26. refreshSession()
  27. getUser()
  28. setSession(...)
  29. addListener('authStateChange', ...)
  30. removeAllListeners()
  31. select(...)
  32. insert(...)
  33. update(...)
  34. delete(...)
  35. getPluginVersion()
  36. Interfaces
  37. Type Aliases
  38. License

@capgo/capacitor-supabase

Use the native Supabase SDKs from your Capacitor app for auth and database calls, and get JWTs for your web layer.

Capgo - Build Capacitor apps with AI, ship updates instantly

Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.

➡️ Get started for free

14-day unlimited free trial. No credit card required

🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use @capgo/capacitor-supabase in your Capacitor app: npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/capacitor-supabase to my Capacitor app and wire it up." Agent setup guides · Hosted MCP

@capgo/capacitor-supabase for Capacitor apps

Key features

  • Auth methods: email and password, sign up, anonymous, OAuth providers and OTP with verifyOtp().
  • Sessions: getSession(), refreshSession(), setSession(), getUser() and signOut(), with the authStateChange event.
  • JWT access: sessions include the access token for your own API calls.
  • Database: select(), insert(), update() and delete() on your tables.
  • Native SDKs: supabase-swift on iOS and supabase-kt on Android.
  • Platforms: iOS and Android. On web, use @supabase/supabase-js directly.

Why Capacitor Supabase?

A native Supabase SDK integration that provides real native authentication with JWT token access for your Capacitor apps:

  • Native SDK integration - Full access to Supabase's native iOS and Android SDKs
  • JWT token access - Get JWT tokens from native auth for use in JavaScript/web layers
  • Complete auth methods - Email/password, OAuth, OTP, magic links, and more
  • Session management - Native session handling with automatic token refresh
  • Database operations - Native CRUD operations for Supabase tables
  • Auth state listeners - Real-time auth state change events
  • Hybrid approach - Use native auth with supabase-js for database queries
  • Free and open source - No paid services required

Perfect for apps that need secure native authentication while leveraging Supabase's powerful backend services.

Why only Auth and basic DB operations? The Supabase JS SDK already works great in Capacitor for most features (Realtime, Storage, Edge Functions, etc.). Building native bridges for every feature would add complexity without real benefits. This plugin focuses on authentication where native SDKs provide actual value (secure token storage, OAuth flows, biometrics). For everything else, just use @supabase/supabase-js with the JWT from native auth.

Why not bridge everything natively?

  • No performance gain - The bridge overhead (JSON serialization/deserialization between JS and native) negates any benefit from skipping HTTP preflight requests. You're just moving the transformation cost from network to CPU.
  • Type safety issue - Native SDKs require typed models for every table/query. You'd need to define Swift/Kotlin types for your entire database schema and keep them in sync. With JS, you get dynamic typing that just works.
  • Maintenance burden - Every Supabase SDK update would require updating 3 codebases (JS, iOS, Android) instead of just one. The JS SDK is already well-maintained by Supabase.

Documentation

The most complete doc is available here: https://capgo.app/docs/plugins/supabase/

Compatibility

Plugin versionCapacitor compatibilityMaintained
v8.*.*v8.*.*✅
v7.*.*v7.*.*On demand
v6.*.*v6.*.*❌
v5.*.*v5.*.*❌

Note: The major version of this plugin follows the major version of Capacitor. Use the version that matches your Capacitor installation (e.g., plugin v8 for Capacitor 8). Only the latest major version is actively maintained.

Install

You can use our AI-Assisted Setup to install the plugin. Add the Capgo skills to your AI tool using the following command:

npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-plugins

Then use the following prompt:

Use the `capacitor-plugins` skill from `cap-go/capacitor-skills` to install the `@capgo/capacitor-supabase` plugin in my project.

If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:

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' }
});

Sign In Anonymously

const { session, user } = await CapacitorSupabase.signInAnonymously();
console.log('Anonymous user ID:', user?.id);

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.

ParamTypeDescription
optionsSupabaseConfig- Configuration options including URL and API key

Since: 0.0.1


signInWithPassword(...)

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

Sign in with email and password.

ParamTypeDescription
optionsSignInWithPasswordOptions- 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.

ParamTypeDescription
optionsSignUpOptions- Email, password, and optional user metadata

Returns: Promise<AuthResult>

Since: 0.0.1


signInAnonymously()

signInAnonymously() => Promise<AuthResult>

Sign in anonymously. Creates a temporary guest session without requiring credentials.

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.

ParamTypeDescription
optionsSignInWithOAuthOptions- 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.

ParamTypeDescription
optionsSignInWithOtpOptions- Email or phone number to send OTP to

Since: 0.0.1


verifyOtp(...)

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

Verify an OTP token.

ParamTypeDescription
optionsVerifyOtpOptions- 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.

ParamTypeDescription
optionsSetSessionOptions- 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.

ParamTypeDescription
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.

ParamTypeDescription
optionsSelectOptions- 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.

ParamTypeDescription
optionsInsertOptions- 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.

ParamTypeDescription
optionsUpdateOptions- 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.

ParamTypeDescription
optionsDeleteOptions- 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.

PropTypeDescriptionSince
supabaseUrlstringThe Supabase project URL.0.0.1
supabaseKeystringThe Supabase anonymous/public key.0.0.1

AuthResult

Result of authentication operations that return a session.

PropTypeDescriptionSince
sessionSession | nullThe session if authentication was successful.0.0.1
userUser | nullThe authenticated user if successful.0.0.1

Session

Session object containing authentication tokens.

PropTypeDescriptionSince
accessTokenstringThe JWT access token. Use this for authenticated API requests.0.0.1
refreshTokenstringThe refresh token for obtaining new access tokens.0.0.1
tokenTypestringToken type (usually "bearer").0.0.1
expiresInnumberNumber of seconds until the access token expires.0.0.1
expiresAtnumberUnix timestamp when the token expires.0.0.1
userUserThe authenticated user.0.0.1

User

User object returned from authentication operations.

PropTypeDescriptionSince
idstringUnique identifier for the user.0.0.1
emailstringUser's email address.0.0.1
phonestringUser's phone number.0.0.1
createdAtstringTimestamp when the user was created.0.0.1
lastSignInAtstringTimestamp when the user last signed in.0.0.1
userMetadataRecord<string, unknown>User metadata (custom fields).0.0.1
appMetadataRecord<string, unknown>App metadata.0.0.1

SignInWithPasswordOptions

Options for email/password sign-in.

PropTypeDescriptionSince
emailstringUser's email address.0.0.1
passwordstringUser's password.0.0.1

SignUpOptions

Options for email/password sign-up.

PropTypeDescriptionSince
emailstringUser's email address.0.0.1
passwordstringUser's password.0.0.1
dataRecord<string, unknown>Optional user metadata to store with the user.0.0.1

SignInWithOAuthOptions

Options for OAuth sign-in.

PropTypeDescriptionSince
providerOAuthProviderThe OAuth provider to use.0.0.1
redirectTostringURL to redirect to after authentication.0.0.1
scopesstringOAuth scopes to request.0.0.1

SignInWithOtpOptions

Options for OTP sign-in.

PropTypeDescriptionSince
emailstringUser's email address (required if phone is not provided).0.0.1
phonestringUser's phone number (required if email is not provided).0.0.1
shouldCreateUserbooleanIf set to false, this method will not create a new user. Defaults to true.8.1.1

VerifyOtpOptions

Options for verifying OTP.

PropTypeDescriptionSince
emailstringUser's email address (required if phone is not provided).0.0.1
phonestringUser's phone number (required if email is not provided).0.0.1
tokenstringThe 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.

PropTypeDescriptionSince
accessTokenstringThe access token.0.0.1
refreshTokenstringThe refresh token.0.0.1

PluginListenerHandle

PropType
remove() => Promise<void>

AuthStateChange

Auth state change callback data.

PropTypeDescriptionSince
eventAuthChangeEventThe type of auth event.0.0.1
sessionSession | nullThe current session (null if signed out).0.0.1

QueryResult

Result of database queries.

PropTypeDescriptionSince
dataT | nullThe query result data.0.0.1
errorstring | nullError message if the query failed.0.0.1
countnumberNumber of affected rows (for insert/update/delete).0.0.1

SelectOptions

Options for database select queries.

PropTypeDescriptionSince
tablestringThe table name to query.0.0.1
columnsstringColumns to select (default: "*").0.0.1
filterRecord<string, unknown>Filter conditions as key-value pairs.0.0.1
limitnumberMaximum number of rows to return.0.0.1
offsetnumberNumber of rows to skip.0.0.1
orderBystringColumn to order by.0.0.1
ascendingbooleanOrder direction.0.0.1
singlebooleanReturn a single row instead of an array.0.0.1

InsertOptions

Options for database insert queries.

PropTypeDescriptionSince
tablestringThe table name to insert into.0.0.1
valuesRecord<string, unknown> | Record<string, unknown>[]The data to insert (single object or array of objects).0.0.1

UpdateOptions

Options for database update queries.

PropTypeDescriptionSince
tablestringThe table name to update.0.0.1
valuesRecord<string, unknown>The data to update.0.0.1
filterRecord<string, unknown>Filter conditions to match rows to update.0.0.1

DeleteOptions

Options for database delete queries.

PropTypeDescriptionSince
tablestringThe table name to delete from.0.0.1
filterRecord<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

版本与发布记录

@capgo/capacitor-supabase 共发布 21 个版本,首次发布于 2026/01/14;过去 12 个月发布了 21 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.2.7latest2026/10/1525 天前
8.2.62026/10/1327 天前
8.2.52026/10/091 个月前
8.2.42026/10/081 个月前
8.2.32026/10/081 个月前
8.2.22026/09/171 个月前

关于 @capgo/capacitor-supabase 的常见问题

@capgo/capacitor-supabase 是什么?

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

如何安装 @capgo/capacitor-supabase?

在项目目录运行 npm install @capgo/capacitor-supabase,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capgo/capacitor-supabase 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@capgo/capacitor-supabase 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capgo/capacitor-supabase 可以商用吗?

@capgo/capacitor-supabase 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@capgo/capacitor-supabase 的下载量有多少?

根据 npm 官方下载统计,@capgo/capacitor-supabase 在 2026/10/09 – 2026/11/07 这 30 天内被下载 17,499 次,日均约 583 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@capgo/capacitor-supabase 还在维护吗?

最新版本 8.2.7 发布于 2026/10/15(25 天前);至今共发布 21 个版本,其中过去 12 个月发布了 21 个;首次发布于 2026/01/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。