Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 17 additions & 148 deletions apps/docs/content/guides/auth/quickstarts/react-native.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -66,48 +66,21 @@ hideToc: true

Create a helper file `lib/supabase.ts` that exports a Supabase client using your Project URL and key.

Create a `.env` file and populate with your Supabase connection variables:

<ProjectConfigVariables variable="url" />
<ProjectConfigVariables variable="publishable" />
<ProjectConfigVariables variable="anon" />

</StepHikeCompact.Details>
<StepHikeCompact.Code>

<$CodeSample
path="/auth/quickstarts/react-native/lib/supabase.ts"
lines={[[1, -1]]}
meta="name=lib/supabase.ts"
/>

```ts name=lib/supabase.ts
import { AppState, Platform } from 'react-native'
import 'react-native-url-polyfill/auto'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { createClient, processLock } from '@supabase/supabase-js'

const supabaseUrl = YOUR_REACT_NATIVE_SUPABASE_URL
const supabaseAnonKey = YOUR_REACT_NATIVE_SUPABASE_PUBLISHABLE_KEY

export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
auth: {
...(Platform.OS !== "web" ? { storage: AsyncStorage } : {}),
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: false,
lock: processLock,
},
})

// Tells Supabase Auth to continuously refresh the session automatically
// if the app is in the foreground. When this is added, you will continue
// to receive `onAuthStateChange` events with the `TOKEN_REFRESHED` or
// `SIGNED_OUT` event if the user's session is terminated. This should
// only be registered once.
if (Platform.OS !== "web") {
AppState.addEventListener('change', (state) => {
if (state === 'active') {
supabase.auth.startAutoRefresh()
} else {
supabase.auth.stopAutoRefresh()
}
})
}
```
<$Partial path="api_settings_steps.mdx" variables={{ "framework": "exporeactnative", "tab": "mobiles" }} />

</StepHikeCompact.Code>
Expand All @@ -123,91 +96,11 @@ hideToc: true

<StepHikeCompact.Code>

```tsx name=components/Auth.tsx
import React, { useState } from 'react'
import { Alert, StyleSheet, View } from 'react-native'
import { supabase } from '../lib/supabase'
import { Button, Input } from '@rneui/themed'

export default function Auth() {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)

async function signInWithEmail() {
setLoading(true)
const { error } = await supabase.auth.signInWithPassword({
email: email,
password: password,
})

if (error) Alert.alert(error.message)
setLoading(false)
}

async function signUpWithEmail() {
setLoading(true)
const {
data: { session },
error,
} = await supabase.auth.signUp({
email: email,
password: password,
})

if (error) Alert.alert(error.message)
if (!session) Alert.alert('Please check your inbox for email verification!')
setLoading(false)
}

return (
<View style={styles.container}>
<View style={[styles.verticallySpaced, styles.mt20]}>
<Input
label="Email"
leftIcon={{ type: 'font-awesome', name: 'envelope' }}
onChangeText={(text) => setEmail(text)}
value={email}
placeholder="[email protected]"
autoCapitalize={'none'}
/>
</View>
<View style={styles.verticallySpaced}>
<Input
label="Password"
leftIcon={{ type: 'font-awesome', name: 'lock' }}
onChangeText={(text) => setPassword(text)}
value={password}
secureTextEntry={true}
placeholder="Password"
autoCapitalize={'none'}
/>
</View>
<View style={[styles.verticallySpaced, styles.mt20]}>
<Button title="Sign in" disabled={loading} onPress={() => signInWithEmail()} />
</View>
<View style={styles.verticallySpaced}>
<Button title="Sign up" disabled={loading} onPress={() => signUpWithEmail()} />
</View>
</View>
)
}

const styles = StyleSheet.create({
container: {
marginTop: 40,
padding: 12,
},
verticallySpaced: {
paddingTop: 4,
paddingBottom: 4,
alignSelf: 'stretch',
},
mt20: {
marginTop: 20,
},
})
```
<$CodeSample
path="/auth/quickstarts/react-native/components/Auth.tsx"
lines={[[1, -1]]}
meta="name=components/Auth.tsx"
/>

</StepHikeCompact.Code>

Expand All @@ -222,35 +115,11 @@ hideToc: true

<StepHikeCompact.Code>

```tsx name=App.tsx
import 'react-native-url-polyfill/auto'
import { useState, useEffect } from 'react'
import { supabase } from './lib/supabase'
import Auth from './components/Auth'
import { View, Text } from 'react-native'
import { Session } from '@supabase/supabase-js'

export default function App() {
const [session, setSession] = useState<Session | null>(null)

useEffect(() => {
supabase.auth.getSession().then(({ data: { session } }) => {
setSession(session)
})

supabase.auth.onAuthStateChange((_event, session) => {
setSession(session)
})
}, [])

return (
<View>
<Auth />
{session && session.user && <Text>{session.user.id}</Text>}
</View>
)
}
```
<$CodeSample
path="/auth/quickstarts/react-native/App.tsx"
lines={[[1, -1]]}
meta="name=App.tsx"
/>

</StepHikeCompact.Code>

Expand Down
20 changes: 17 additions & 3 deletions apps/studio/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import timezone from 'dayjs/plugin/timezone'
import utc from 'dayjs/plugin/utc'
import Head from 'next/head'
import { NuqsAdapter } from 'nuqs/adapters/next/pages'
import { ErrorInfo, useCallback } from 'react'
import { type ComponentProps, ErrorInfo, useCallback } from 'react'
import { ErrorBoundary } from 'react-error-boundary'

import {
Expand All @@ -53,6 +53,7 @@ import { GlobalErrorBoundaryState } from 'components/ui/ErrorBoundary/GlobalErro
import { useRootQueryClient } from 'data/query-client'
import { customFont, sourceCodePro } from 'fonts'
import { useCustomContent } from 'hooks/custom-content/useCustomContent'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { AuthProvider } from 'lib/auth'
import { API_URL, BASE_PATH, IS_PLATFORM, useDefaultProvider } from 'lib/constants'
import { ProfileProvider } from 'lib/profile'
Expand All @@ -67,6 +68,19 @@ dayjs.extend(timezone)
dayjs.extend(relativeTime)
dayjs.extend(duration)

const FeatureFlagProviderWithOrgContext = ({
children,
...props
}: ComponentProps<typeof FeatureFlagProvider>) => {
const { data: selectedOrganization } = useSelectedOrganizationQuery({ enabled: IS_PLATFORM })

return (
<FeatureFlagProvider {...props} organizationSlug={selectedOrganization?.slug ?? undefined}>
{children}
</FeatureFlagProvider>
)
}

loader.config({
// [Joshen] Attempt for offline support/bypass ISP issues is to store the assets required for monaco
// locally. We're however, only storing the assets which we need (based on what the network tab loads
Expand Down Expand Up @@ -124,7 +138,7 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {
<NuqsAdapter>
<HydrationBoundary state={pageProps.dehydratedState}>
<AuthProvider>
<FeatureFlagProvider
<FeatureFlagProviderWithOrgContext
API_URL={API_URL}
enabled={IS_PLATFORM}
getConfigCatFlags={getConfigCatFlags}
Expand Down Expand Up @@ -180,7 +194,7 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {
<ReactQueryDevtools initialIsOpen={false} buttonPosition="bottom-left" />
)}
</ProfileProvider>
</FeatureFlagProvider>
</FeatureFlagProviderWithOrgContext>
</AuthProvider>
</HydrationBoundary>
</NuqsAdapter>
Expand Down
36 changes: 36 additions & 0 deletions examples/auth/quickstarts/react-native/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files

# dependencies
node_modules/

# Expo
.expo/
dist/
web-build/

# Native
*.orig.*
*.jks
*.p8
*.p12
*.key
*.mobileprovision

# Metro
.metro-health-check*

# debug
npm-debug.*
yarn-debug.*
yarn-error.*

# macOS
.DS_Store
*.pem

# local env files
.env*.local
.env

# typescript
*.tsbuildinfo
27 changes: 27 additions & 0 deletions examples/auth/quickstarts/react-native/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import 'react-native-url-polyfill/auto'
import { useState, useEffect } from 'react'
import { supabase } from './lib/supabase'
import Auth from './components/Auth'
import { View, Text } from 'react-native'
import { User } from '@supabase/supabase-js'

export default function App() {
const [user, setUser] = useState<User | null>(null)

useEffect(() => {
supabase.auth.getUser().then(({ data: { user } }) => {
setUser(user)
})

supabase.auth.onAuthStateChange((_event, session) => {
setUser(session?.user ?? null)
})
}, [])

return (
<View>
<Auth />
{user && <Text>{user.id}</Text>}
</View>
)
}
54 changes: 54 additions & 0 deletions examples/auth/quickstarts/react-native/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Supabase Auth with React Native

This example demonstrates how to use Supabase Auth with React Native and Expo.

## Getting started

### 1. Create a Supabase project

[Launch a new project](https://supabase.com/dashboard) in the Supabase Dashboard.

### 2. Configure environment variables

Create a `.env` file and populate with your Supabase connection variables:

You can find these in your [Supabase Dashboard](https://supabase.com/dashboard/project/_/settings/api) under Settings > API.

### 3. Install dependencies

```bash
npm install
```

### 4. Start the app

```bash
npm start
```

Follow the instructions in the terminal to open the app on your device or emulator.

## Project structure

```
├── App.tsx # Main app component
├── components/
│ └── Auth.tsx # Authentication form component
├── lib/
│ └── supabase.ts # Supabase client configuration
├── app.json # Expo configuration
├── package.json # Dependencies
└── tsconfig.json # TypeScript configuration
```

## Features

- Email/password sign up
- Email/password sign in
- Session persistence with AsyncStorage
- Automatic token refresh

## Learn more

- [Supabase Auth Documentation](https://supabase.com/docs/guides/auth)
- [React Native Quickstart](https://supabase.com/docs/guides/auth/quickstarts/react-native)
28 changes: 28 additions & 0 deletions examples/auth/quickstarts/react-native/app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"expo": {
"name": "Supabase Auth React Native",
"slug": "supabase-auth-react-native",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "light",
"splash": {
"image": "./assets/splash.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"assetBundlePatterns": ["**/*"],
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff"
}
},
"web": {
"favicon": "./assets/favicon.png"
}
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading