### Install Dependencies
Source: https://github.com/descope/descope-react-native/blob/main/example-rn-latest/README.md
Run this command to install project dependencies.
```bash
yarn install
```
--------------------------------
### Start Authentication Flow
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useFlow-deprecated.md
Example of using the start method from the useFlow hook to initiate an authentication flow. It handles the response and manages the session.
```tsx
import { useFlow, useSession } from '@descope/react-native-sdk'
function LoginScreen() {
const { start, exchange } = useFlow()
const { manageSession } = useSession()
const startAuthFlow = async () => {
try {
const resp = await start(
'https://auth.example.com/flows/login',
'https://myapp.example.com/auth',
'myapp://auth'
)
if (resp.ok && resp.data) {
await manageSession(resp.data)
} else {
console.error('Flow failed:', resp.error)
}
} catch (error) {
console.error('Flow error:', error)
}
}
return
```
--------------------------------
### Run Android Example
Source: https://github.com/descope/descope-react-native/blob/main/example/README.md
Build and run the Android example app from the example/ directory.
```bash
yarn android
```
--------------------------------
### Install iOS Pods
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/configuration.md
After cloning the repository or making changes to the `Podfile`, navigate to the `ios` directory and run `pod install` to install the necessary native dependencies for iOS.
```bash
cd ios
pod install
cd ..
```
--------------------------------
### Redux Middleware Example with Helper Functions
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/MANIFEST.txt
This example demonstrates how to use Descope helper functions within a Redux middleware setup for handling authentication-related actions.
```javascript
const descopeMiddleware = store => next => async action => {
const token = getCurrentSessionToken();
const user = getCurrentUser();
// ... middleware logic using token and user
return next(action);
};
```
--------------------------------
### Install iOS CocoaPods
Source: https://github.com/descope/descope-react-native/blob/main/example-rn-latest/README.md
For iOS projects, navigate to the `ios` directory and run this command to install CocoaPods.
```bash
cd ios && pod install
```
--------------------------------
### React Native SDK Test Setup with AuthProvider
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/configuration.md
Example of setting up the AuthProvider for testing in a React Native application. This configuration disables auto-refresh and provides a custom logger and mock fetch function.
```tsx
import { AuthProvider } from '@descope/react-native-sdk'
export function TestAppWrapper({ children }) {
return (
{children}
)
}
```
--------------------------------
### Install Dependencies
Source: https://github.com/descope/descope-react-native/blob/main/example/README.md
Install project dependencies using yarn from the repository root.
```bash
yarn bootstrap
```
--------------------------------
### Basic AuthProvider Setup
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/AuthProvider.md
Demonstrates the basic usage of the AuthProvider component, wrapping the application with the required projectId.
```tsx
import { AuthProvider } from '@descope/react-native-sdk'
export default function AppRoot() {
return (
)
}
```
--------------------------------
### start Method
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useFlow-deprecated.md
Starts a user authentication flow. This method is part of the deprecated `useFlow` hook.
```APIDOC
## start(flowUrl, deepLinkUrl, backupCustomScheme?, authentication?)
### Description
Starts a user authentication flow. This method is deprecated and should be replaced by the `FlowView` component.
### Method
`start`
### Parameters
#### Path Parameters
* **flowUrl** (string) - Required - URL where the flow is hosted
* **deepLinkUrl** (string) - Required - Deep link URL for OAuth/magic link redirects (Android)
* **backupCustomScheme** (string) - Optional - Custom scheme fallback for Android (for browsers that don't honor app links)
* **authentication** (FlowAuthentication) - Optional - Authentication context to run flow as authenticated user
### Returns
`Promise>`
### Behavior
- On iOS: Launches `ASWebAuthenticationSession`
- On Android: Returns immediately; waits for redirect via `exchange()`
- If `authentication` provided, primes the flow with user's refresh JWT
```
--------------------------------
### Install Descope React Native SDK
Source: https://github.com/descope/descope-react-native/blob/main/README.md
Install the Descope SDK for React Native using Yarn or npm. For iOS, run `pod install` in the `ios` directory.
```bash
yarn add @descope/react-native-sdk
# or
npm i --save @descope/react-native-sdk
```
```bash
pod install
```
--------------------------------
### Start Metro Bundler
Source: https://github.com/descope/descope-react-native/blob/main/example-rn-latest/README.md
Run this command in a separate terminal to start the Metro bundler for React Native.
```bash
yarn start
```
--------------------------------
### Migration Example: Before useFlow
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useFlow-deprecated.md
Illustrates the previous implementation using useFlow, including handling deep links for Android and managing the session.
```tsx
import { useFlow, useSession } from '@descope/react-native-sdk'
import { useEffect, useState } from 'react'
import { Linking } from 'react-native'
function LoginScreen() {
const [deepLink, setDeepLink] = useState('')
const { start, exchange } = useFlow()
const { manageSession } = useSession()
useEffect(() => {
Linking.addEventListener('url', (event) => {
setDeepLink(event.url)
})
}, [])
useEffect(() => {
if (deepLink && Platform.OS === 'android') {
exchange(deepLink)
}
}, [deepLink, exchange])
const handleStartFlow = async () => {
const resp = await start(
'https://auth.example.com/flows/login',
'https://myapp.example.com/auth'
)
if (resp.ok && resp.data) {
await manageSession(resp.data)
}
}
return
```
--------------------------------
### Start Metro Bundler
Source: https://github.com/descope/descope-react-native/blob/main/example/README.md
Start the Metro bundler separately in a terminal before running the iOS app.
```bash
yarn start
```
--------------------------------
### FlowOptions Configuration Example
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/MANIFEST.txt
FlowOptions allow for detailed customization of the authentication flow, including appearance, styling, and behavior.
```javascript
const flowOptions = {
appearance: {
// ... styling options
},
customFont: 'MyCustomFont',
// ... other options
};
```
--------------------------------
### Make Authenticated Requests
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/README.md
Example of how to make authenticated API requests using the current session token.
```APIDOC
## Make Authenticated Requests
```tsx
import { getCurrentSessionToken } from '@descope/react-native-sdk'
const token = getCurrentSessionToken()
fetch('/api/endpoint', {
headers: { Authorization: `Bearer ${token}` }
})
```
```
--------------------------------
### Starting an Authenticated Flow (Deprecated)
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/types.md
Illustrates the deprecated usage of the `useFlow` hook to start a flow as an authenticated user, passing the necessary `FlowAuthentication` context which includes the `flowId` and `refreshJwt` obtained from the active session.
```tsx
// Deprecated - use FlowView instead
const { start } = useFlow()
const { session } = useSession()
const runAuthenticatedFlow = async () => {
if (!session) return
const response = await start(
'https://my-flow.example.com',
'https://my-app.example.com/auth',
undefined,
{
flowId: 'step-up-auth-flow',
refreshJwt: session.refreshJwt,
}
)
}
```
--------------------------------
### FlowView Component Usage
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/types.md
Example of how to use the FlowView component with specific FlowOptions, deep linking, and callback handlers.
```typescript
import { FlowView } from '@descope/react-native-sdk'
```
--------------------------------
### Using FlowView for Authentication
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useFlow-deprecated.md
This example demonstrates how to use the `FlowView` component for handling authentication flows, including deep link integration and session management. It replaces the deprecated `useFlow` hook.
```tsx
import { FlowView, useHostedFlowUrl, useSession } from '@descope/react-native-sdk'
import { useEffect, useState } from 'react'
import { Linking } from 'react-native'
function LoginScreen() {
const [deepLink, setDeepLink] = useState('')
const flowUrl = useHostedFlowUrl('my-auth-flow')
const { manageSession } = useSession()
useEffect(() => {
Linking.getInitialURL().then((url) => {
if (url) setDeepLink(url)
})
const subscription = Linking.addEventListener('url', (event) => {
setDeepLink(event.url)
})
return () => subscription.remove()
}, [])
return (
{
await manageSession(jwt)
}}
onError={(error) => {
console.error('Flow error:', error)
}}
/>
)
}
```
--------------------------------
### Network Interceptor Setup
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/helpers.md
Shows how to create a global request interceptor using `getCurrentSessionToken` to dynamically add the Authorization header. This is useful for intercepting all outgoing requests.
```typescript
import { getCurrentSessionToken } from '@descope/react-native-sdk'
// Set up a global request interceptor
const createAuthenticatedRequest = (url: string, options: RequestInit = {}) => {
const token = getCurrentSessionToken()
return fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': token ? `Bearer ${token}` : '',
},
})
}
// Use in your app
const data = await createAuthenticatedRequest('/api/user/profile')
```
--------------------------------
### Setup Analytics with User Info
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/helpers.md
Demonstrates how to use `getCurrentUser` to retrieve user details for setting up analytics tracking outside of React components. Ensures user data is available for logging and tracking.
```typescript
import { getCurrentUser } from '@descope/react-native-sdk'
// Setup user tracking in analytics
function setupAnalytics() {
const user = getCurrentUser()
if (user) {
myAnalytics.setUser({
id: user.userId,
email: user.email,
name: user.name,
})
}
}
```
--------------------------------
### Authenticate Users with useDescope Hook (OTP Example)
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/INDEX.md
Utilize the useDescope hook for direct integration of authentication methods like OTP verification. This provides more granular control over the authentication process.
```tsx
import { useDescope, useSession } from '@descope/react-native-sdk'
function OtpScreen() {
const descope = useDescope()
const { manageSession } = useSession()
const verifyOtp = async (email, code) => {
const resp = await descope.otp.email.verify(email, code)
if (resp.ok && resp.data) {
await manageSession(resp.data)
}
}
return
}
```
--------------------------------
### SDK Structure - SAML/SSO Authentication
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useDescope.md
Defines the structure for SAML and SSO authentication methods, including starting the flow and exchanging codes.
```typescript
type Sdk = {
// ... other namespaces
// SAML/SSO Authentication
saml: {
start(tenant: string, redirectUrl?: string): Promise>
exchange(code: string): Promise>
}
// SSO
sso: {
start(domain: string, redirectUrl?: string): Promise>
exchange(code: string): Promise>
}
// ... other namespaces
```
--------------------------------
### Manual Session Refresh Example
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/helpers.md
Illustrates how to manually refresh a session using `getCurrentRefreshToken` and `descope.refresh`. This approach is not recommended for most use cases, which should prefer `useSession().refreshSessionIfAboutToExpire()`.
```typescript
import { useDescope, useSession } from '@descope/react-native-sdk'
import { getCurrentRefreshToken } from '@descope/react-native-sdk'
function ManualRefresh() {
const descope = useDescope()
const { updateTokens } = useSession()
const refreshManually = async () => {
const refreshToken = getCurrentRefreshToken()
if (!refreshToken) {
console.log('No active session to refresh')
return
}
const resp = await descope.refresh(refreshToken)
if (resp.ok && resp.data) {
await updateTokens(resp.data.sessionJwt, resp.data.refreshJwt)
console.log('Session refreshed successfully')
} else {
console.error('Refresh failed:', resp.error)
}
}
return
}
```
--------------------------------
### Authenticated API Client Class
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/helpers.md
An example of an API client class that automatically includes authentication headers for requests. It uses `getCurrentSessionToken` to fetch the token.
```tsx
import { getCurrentSessionToken } from '@descope/react-native-sdk'
class ApiClient {
private baseUrl: string
constructor(baseUrl: string) {
this.baseUrl = baseUrl
}
private getAuthHeaders(): HeadersInit {
const token = getCurrentSessionToken()
return {
'Authorization': token ? `Bearer ${token}` : '',
'Content-Type': 'application/json',
}
}
async get(endpoint: string): Promise {
const response = await fetch(`${this.baseUrl}${endpoint}`, {
method: 'GET',
headers: this.getAuthHeaders(),
})
if (!response.ok) {
throw new Error(`API error: ${response.status}`)
}
return response.json()
}
async post(endpoint: string, body: unknown): Promise {
const response = await fetch(`${this.baseUrl}${endpoint}`, {
method: 'POST',
headers: this.getAuthHeaders(),
body: JSON.stringify(body),
})
if (!response.ok) {
throw new Error(`API error: ${response.status}`)
}
return response.json()
}
}
export const apiClient = new ApiClient('https://api.example.com')
```
--------------------------------
### Check Session on App Startup
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useSession.md
Conditionally render UI components based on the session state and loading status when the application starts. This ensures the correct screen (e.g., login or main app) is displayed after loading.
```tsx
import { useEffect } from 'react'
import { useSession } from '@descope/react-native-sdk'
function RootScreen() {
const { session, isSessionLoading } = useSession()
if (isSessionLoading) {
return
}
return session ? :
}
```
--------------------------------
### Deprecated useFlow Hook Methods
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/MANIFEST.txt
The useFlow hook is deprecated. It previously provided methods like start(), resume(), and exchange() for managing authentication flows.
```javascript
import { useFlow } from '@descope/react-native-sdk';
const { start, resume, exchange } = useFlow();
```
--------------------------------
### SDK Structure - Low-level HTTP Client
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useDescope.md
Defines the structure for the low-level HTTP client, providing methods for GET, POST, PUT, and DELETE requests.
```typescript
type Sdk = {
// ... other namespaces
// Low-level HTTP
httpClient: {
get(path: string, init?: RequestInit): Promise
post(path: string, body?: unknown, init?: RequestInit): Promise
put(path: string, body?: unknown, init?: RequestInit): Promise
delete(path: string, init?: RequestInit): Promise
}
}
```
--------------------------------
### Self-Hosted Flow URL Construction
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useHostedFlowUrl.md
Provides an example of how to manually construct a URL for self-hosted Descope flows when not using the `useHostedFlowUrl` hook. This is for scenarios where flows are hosted on a custom domain.
```tsx
export function AuthScreen() {
// Use your own hosted flow URL instead of useHostedFlowUrl
const flowUrl = 'https://auth.mycompany.example.com/flows/sign-in'
return (
)
}
```
--------------------------------
### Initialize App with Auth
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/README.md
Steps to initialize the Descope authentication provider and check the initial session state.
```APIDOC
## Initialize App with Auth
1. Wrap app with ``
2. Check `useSession().isSessionLoading` on startup
3. Render login or home based on `session` state
```
--------------------------------
### Environment Configuration
Source: https://github.com/descope/descope-react-native/blob/main/example/README.md
Copy the environment template and fill in Descope project details in the .env file.
```bash
cp .env.example .env
```
```plaintext
DESCOPE_PROJECT_ID=your_project_id
DESCOPE_BASE_URL=
DESCOPE_FLOW_ID=sign-up-or-in
DESCOPE_AUTHENTICATED_FLOW_ID=update-user-details
```
--------------------------------
### Initialize AuthProvider
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/INDEX.md
Wrap your application with the AuthProvider at the root to initialize the Descope SDK and manage authentication state.
```tsx
import { AuthProvider } from '@descope/react-native-sdk'
export function App() {
return (
)
}
```
--------------------------------
### Implement Login - FlowView
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/README.md
Recommended method for implementing user login using the `FlowView` component.
```APIDOC
**Option A - FlowView (Recommended)**
1. Get flow URL with `useHostedFlowUrl(flowId)` or use custom URL
2. Render `>
exchange(code: string, codeVerifier: string): Promise>
}
// ... other namespaces
```
--------------------------------
### useFlow Hook Signature
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useFlow-deprecated.md
The `useFlow` hook is deprecated and should not be used. It returns a `DescopeFlow` interface with methods to start, resume, and exchange authentication flows.
```APIDOC
## useFlow Hook Signature
```tsx
function useFlow(): DescopeFlow
```
### Description
This hook is deprecated. It provides access to methods for managing authentication flows.
### Return Type
Returns a `DescopeFlow` interface with the following methods:
```tsx
interface DescopeFlow {
start(flowUrl: string, deepLinkUrl: string, backupCustomScheme?: string, authentication?: FlowAuthentication): Promise>
resume(incomingUrl: string): Promise
exchange(incomingUrl: string): Promise
}
```
```
--------------------------------
### Copy Environment Template
Source: https://github.com/descope/descope-react-native/blob/main/example-expo/README.md
Copy the environment template file to create a new .env file for Descope project configuration.
```bash
cp .env.example .env
```
--------------------------------
### SDK Structure - Session Management
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useDescope.md
Defines the structure for session management operations including refreshing tokens, getting user info, and logging out.
```typescript
type Sdk = {
// ... other namespaces
// Session Management
refresh(refreshJwt: string): Promise>
me(refreshJwt: string): Promise>
logout(refreshJwt: string): Promise>
// ... other namespaces
```
--------------------------------
### Handling SDK Responses
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/errors.md
Demonstrates the recommended pattern for handling SDK responses by checking the 'ok' property. Access 'resp.data' on success and 'resp.error' on failure.
```typescript
const resp = await descope.otp.email.verify(email, code)
if (resp.ok) {
// Success: resp.data is available
const { sessionJwt, refreshJwt, user } = resp.data
} else {
// Error: resp.error is available
const { errorCode, errorDescription } = resp.error!
}
```
--------------------------------
### Implement Login - Manual Auth
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/README.md
Alternative method for implementing user login by manually calling authentication functions.
```APIDOC
**Option B - Manual Auth**
1. Get `descope` from `useDescope()`
2. Call `descope.otp.email.sendCode()` or other auth method
3. Call `descope.otp.email.verify()` to get JWT
4. Call `manageSession(jwt)` from `useSession()`
```
--------------------------------
### Configure Descope Environment Variables
Source: https://github.com/descope/descope-react-native/blob/main/example-expo/README.md
Edit the .env file to include your Descope project ID, base URL, and flow IDs. The authenticated flow ID should point to a flow expecting a signed-in user.
```bash
EXPO_PUBLIC_DESCOPE_PROJECT_ID=your_project_id
EXPO_PUBLIC_DESCOPE_BASE_URL=
EXPO_PUBLIC_DESCOPE_FLOW_ID=sign-up-or-in
EXPO_PUBLIC_DESCOPE_AUTHENTICATED_FLOW_ID=update-user-details
```
--------------------------------
### Get Current Session Token
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/helpers.md
Retrieves the current session JWT. Returns an empty string if no session is active. Useful for setting Authorization headers.
```typescript
function getCurrentSessionToken(): string
```
--------------------------------
### Configure AuthProvider with Custom Logger
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/types.md
Demonstrates how to wrap your application with AuthProvider and provide a custom logger implementation for SDK events. Ensure the logger methods match the expected interface.
```tsx
import { AuthProvider } from '@descope/react-native-sdk'
const logger = {
log: (message) => myService.info(message),
debug: (message) => myService.debug(message),
warn: (message) => myService.warn(message),
error: (message) => myService.error(message),
}
```
--------------------------------
### Axios Interceptor Setup
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/helpers.md
Configures an Axios interceptor to automatically attach the session token to request headers using `getCurrentSessionToken`. This simplifies API calls made with Axios.
```typescript
import axios from 'axios'
import { getCurrentSessionToken } from '@descope/react-native-sdk'
const apiClient = axios.create()
apiClient.interceptors.request.use((config) => {
const token = getCurrentSessionToken()
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
export default apiClient
```
--------------------------------
### Wrap App with AuthProvider
Source: https://github.com/descope/descope-react-native/blob/main/README.md
Wrap your application's root component with the AuthProvider, providing your Descope Project ID. Optionally, set a `baseUrl` if your Descope project manages tokens in cookies.
```javascript
import { AuthProvider } from '@descope/react-native-sdk'
const AppRoot = () => {
return (
)
}
```
--------------------------------
### Get Current User Details
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useDescope.md
Fetches and displays the current logged-in user's details. It also persists the fetched user data to the session for later use.
```tsx
import { useDescope, useSession } from '@descope/react-native-sdk'
export function UserProfileScreen() {
const descope = useDescope()
const { session, updateUser } = useSession()
const [user, setUser] = useState(null)
const fetchUserDetails = async () => {
if (!session) return
const resp = await descope.me(session.refreshJwt)
if (resp.ok && resp.data) {
setUser(resp.data)
await updateUser(resp.data) // persist to session
} else {
console.error('Failed to fetch user:', resp.error)
}
}
useEffect(() => {
fetchUserDetails()
}, [])
return user ? (
Name: {user.name}Email: {user.email}
) : null
}
```
--------------------------------
### Get Current Refresh Token
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/helpers.md
Retrieves the current refresh JWT. Returns an empty string if no session is active. Note: `refreshSessionIfAboutToExpire()` is generally preferred over manual refresh.
```typescript
function getCurrentRefreshToken(): string
```
--------------------------------
### FlowView with Custom Styling
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/FlowView.md
Applies custom styles to the FlowView component to integrate it seamlessly with the application's layout and design. This example uses StyleSheet for defining container styles.
```tsx
import { StyleSheet } from 'react-native'
import { FlowView } from '@descope/react-native-sdk'
const styles = StyleSheet.create({
flowContainer: {
flex: 1,
backgroundColor: '#f5f5f5',
},
})
console.log('Flow is ready')}
onSuccess={handleSuccess}
onError={handleError}
/>
```
--------------------------------
### Run on Android
Source: https://github.com/descope/descope-react-native/blob/main/example-rn-latest/README.md
Execute this command to build and run the React Native application on an Android device or emulator.
```bash
yarn android
```
--------------------------------
### Get Current User Information
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/helpers.md
Retrieves the current user's profile information. Returns `undefined` if no session is active. Useful for accessing user details in non-component contexts.
```typescript
function getCurrentUser(): UserResponse | undefined
```
--------------------------------
### Check Session on Startup
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/INDEX.md
Use the useSession hook in your root screen to determine the user's authentication status and conditionally render the app or login flow.
```tsx
import { useSession } from '@descope/react-native-sdk'
function RootScreen() {
const { session, isSessionLoading } = useSession()
if (isSessionLoading) {
return
}
return session ? :
}
```
--------------------------------
### Handle Logout Gracefully with useSession
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useSession.md
Demonstrates how to log out a user, attempting to notify the server and always clearing the local session before navigating to the login screen. Requires `session`, `clearSession` from `useSession`, and `descope` from `useDescope`.
```tsx
const { session, clearSession } = useSession()
const descope = useDescope()
const logout = async () => {
// Try to notify server
try {
if (session) {
await descope.logout(session.refreshJwt)
}
} catch (error) {
console.warn('Server logout failed:', error)
}
// Always clear local session
await clearSession()
// Navigate to login screen
navigation.reset({ index: 0, routes: [{ name: 'Login' }] })
}
```
--------------------------------
### SDK Structure - WebAuthn/Passkeys
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useDescope.md
Defines the structure for WebAuthn and Passkeys authentication, covering sign-up and sign-in flows.
```typescript
type Sdk = {
// ... other namespaces
// WebAuthn / Passkeys
webauthn: {
signUpStart(user?: WebAuthnUser): Promise>
signUpFinish(transactionId: string, credential: CredentialCreationOptions): Promise>
signInStart(): Promise>
signInFinish(transactionId: string, credential: CredentialAssertionOptions): Promise>
}
// ... other namespaces
```
--------------------------------
### FlowView Component
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/MANIFEST.txt
The authentication flow component that renders Descope's hosted authentication flows. It supports configuration via FlowOptions and platform-specific setup for deep linking and social logins.
```APIDOC
## FlowView Component
### Description
The authentication flow component that renders Descope's hosted authentication flows. It supports configuration via FlowOptions and platform-specific setup for deep linking and social logins.
### Props
- **FlowOptions** (object) - Required - Configuration for the authentication flow, including flow ID, redirect URLs, and styling.
- **onSuccess** (function) - Callback function executed upon successful authentication.
- **onError** (function) - Callback function executed upon encountering an error during the flow.
```
--------------------------------
### Passing Client Inputs with useHostedFlowUrl
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useHostedFlowUrl.md
Demonstrates how to pass custom client-side inputs to a Descope flow using the `clientInputs` option within `flowOptions` when using `useHostedFlowUrl`.
```tsx
import { FlowView, useHostedFlowUrl, useSession } from '@descope/react-native-sdk'
export function SignupFlowScreen() {
const flowUrl = useHostedFlowUrl('sign-up-flow')
const { manageSession } = useSession()
return (
{
await manageSession(jwtResponse)
}}
onError={(error) => {
console.error('Signup flow error:', error)
}}
/>
)
}
```
--------------------------------
### FlowView Component Props and Configuration
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/MANIFEST.txt
The FlowView component handles authentication flows. It accepts props and FlowOptions for customization, including iOS and Android setup for deep linking and social sign-in.
```markdown
FlowView
flowOptions={{
// ... FlowOptions configuration
// e.g., appearance, custom font, etc.
}}
onSuccess={handleFlowSuccess}
onError={handleFlowError}
>
```
--------------------------------
### Error Handling in Descope SDK
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useDescope.md
Demonstrates how to check the `ok` property of SDK responses to handle success and error cases. Access `resp.data` on success and `resp.error` on failure.
```tsx
const resp = await descope.otp.email.sendCode('user@example.com')
if (resp.ok) {
// Success: resp.data is available
console.log('Code sent successfully')
} else {
// Error: resp.error is available
console.error('Error code:', resp.error?.errorCode)
console.error('Description:', resp.error?.errorDescription)
}
```
--------------------------------
### Open iOS Workspace
Source: https://github.com/descope/descope-react-native/blob/main/example/README.md
Open the iOS workspace in Xcode for development and building.
```bash
open ios/DescopeReactNativeExample.xcworkspace
```
--------------------------------
### Apply Custom Styles to FlowView
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/configuration.md
Customize the layout of the `FlowView` component by passing a React Native `ViewStyle` object to the `style` prop. This example demonstrates setting a flex-1 container with a light gray background.
```tsx
const styles = StyleSheet.create({
flowContainer: {
flex: 1,
backgroundColor: '#f5f5f5',
},
})
```
--------------------------------
### Handle Session Refresh - Manual
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/README.md
Instructions for manually refreshing the session before critical requests.
```APIDOC
**Manual**
- Call `useSession().refreshSessionIfAboutToExpire()` before critical requests
- Or use custom refresh logic with `descope.refresh()`
```
--------------------------------
### Basic AuthProvider Configuration
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/configuration.md
The AuthProvider component is the main configuration point for the SDK. It requires a projectId and can optionally accept a baseUrl, logger, and fetch implementation.
```tsx
{children}
```
--------------------------------
### AuthProvider with Project ID
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/configuration.md
Configure the AuthProvider with your Descope project ID. This is a required field for initializing the SDK.
```tsx
```
--------------------------------
### Managing Multiple Flows with useHostedFlowUrl
Source: https://github.com/descope/descope-react-native/blob/main/_autodocs/useHostedFlowUrl.md
Illustrates how to manage multiple Descope flows within the same application by conditionally generating URLs based on the current screen state.
```tsx
import { FlowView, useHostedFlowUrl, useSession } from '@descope/react-native-sdk'
export function AuthNav() {
const [screen, setScreen] = useState('login')
const loginUrl = useHostedFlowUrl('sign-in-flow')
const signupUrl = useHostedFlowUrl('sign-up-flow')
const { manageSession } = useSession()
const handleSuccess = async (jwtResponse) => {
await manageSession(jwtResponse)
// Navigation to home happens after session is set
}
const flowUrl = screen === 'login' ? loginUrl : signupUrl
return (
<>
console.error(error)}
/>