React Native & PHP Quickstart

This is a quickstart guide to help you integrate Descope with your React Native & PHP application. Follow the steps below to get started.

Include the Descope React Native Package

Incorporate the Descope React Native SDK as a package. Run the following command:

Terminal
npm i --save @descope/react-native-sdk

Import the React Native SDK

Proceed to import the Descope React Native package.

App.js
import { useCallback } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { AuthProvider, useFlow, useDescope, useSession } from '@descope/react-native-sdk' // <-- Import the Descope React Native SDK
 
export default function App() {
	// ...
}

Initialize Descope with a Custom Project ID

Wrap your app with the Auth Provider and pass in the Descope Project ID (found on your Descope project page). This is needed to activate the SDK.

Note

Optionally, add the baseUrl parameter if using a custom domain in your Descope project (ex: https://auth.company.com).

App.js
export default function App() {
  return (
    <AuthProvider projectId="__ProjectID__"> {/* <-- Add your Descope Project ID */}
	  {/* ... */}
    </AuthProvider>
  );
}

Define and Host Your Flow

Your Descope console provides customizable, predefined authentication flows which are hosted for you. You can also host the flow yourself. You'll use the url of the hosted flow later in your code.

App.js
export default function App() {
  const flow = useFlow()
 
  const startFlow = async () => {
    try {
      const resp = await flow.start('https://auth.descope.io/login/__ProjectID__', '<URL_FOR_APP_LINK>')
      await manageSession(resp.data)
    } catch (e) {
      // handle errors
    }
  }
 
  return (
    <AuthProvider projectId="__ProjectID__">
	  {/* ... */}
    </AuthProvider>
  );
}

For Android (iOS works with just a flow url), follow the instructions in our README to establish App Links, create an activity, and handle token exchange.

Launch Your Flow

Use the flow 'start' function to initiate authentication with a custom flow (URL from step 6). For Android, add the deep link (URL from step 7).

Note

If you need to support Magic Link redirects, follow the steps in our README.

Leverage React Native SDK's Hooks and Session Management Functions

Descope provides many different hooks to check if the user is authenticated, session is loading etc. You can use these to customize the user experience:

  • useSession - This is used for implementing loading screens while sessions are being established (check session), getting user information (session.user.name), etc.
  • useDescope - Exposes the Descope SDK to your app for additional customization (e.g., descope.logout()).
  • useFlow - Used for handling flow related events (e.g., flow.start()).

For more specifics on implementing Session Management, check out our Mobile Session Validation page.

For backend Session Validation, continue reading!

App.js
export default function App() {
  const flow = useFlow()
 
  const { session, clearSession, manageSession } = useSession()
  const { logout } = useDescope()
 
  const handleLogout = useCallback(() => {
    logout()
  }, [logout])
 
  const startFlow = async () => {
    try {
      const resp = await flow.start('https://auth.descope.io/login/__ProjectID__', '<URL_FOR_APP_LINK>')
      await manageSession(resp.data)
    } catch (e) {
      // handle errors
    }
  }
 
  const exampleFetch = async () => {
    const res = await fetch('/path/to/server/api', {
      headers: {
        Authorization: `Bearer ${session.sessionJwt}`,
      },
    })
  }
 
  return (
    <AuthProvider projectId="__ProjectID__">
	  {session ? (
        <View style={styles.container}>
          <Text>Welcome! {session.user.name}</Text>
          <Button onPress={handleLogout} title="Logout" />
        </View>
     ) : (
        <View style={styles.container}>
          <Text>Welcome!</Text>
          <Button onPress={startFlow} title="Start Flow" />
        </View>
     )}
    </AuthProvider>
  );
}
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

At this point, you're done with the frontend. If you would like to also handle Session Management in your backend, keep on reading!

Install Backend SDK

Install the SDK with Composer using the following command:

Terminal
composer require descope/descope-php

Set up Environment file

Create a .env file in the root directory of your project with your Descope Project ID, which can be found in the Console

If you plan to use Management functions, include a Descope Management Key here as well, which can be found here.

DESCOPE_PROJECT_ID=<Descope Project ID>
DESCOPE_MANAGEMENT_KEY=<Descope Management Key>

Setup Backend SDK

You'll need to initialize a DescopeSDK object using your Project ID.

If you're using a custom domain with your Descope project, make sure to export the Base URL (e.g. export DESCOPE_BASE_URI="https://api.descope.com") when initializing descope_client.

require 'vendor/autoload.php';
use Descope\SDK\DescopeSDK;
 
$descopeSDK = new DescopeSDK([
    'projectId' => $_ENV['DESCOPE_PROJECT_ID'],
    'managementKey' => $_ENV['DESCOPE_MANAGEMENT_KEY'] // Optional, only used for Management functions
]);

Implement Session Validation

You will need to then fetch the session token from the Authorization header of each request, and use the SDK to validate the token.

The frontend SDK will store the session token in either a cookie or your browser's local storage. If using a cookie, the token will be sent to your app server automatically with every request.

The $descopeSDK->verify($sessionToken) function can be used to verify a user's session as shown below. This returns a TRUE or FALSE depending on if the JWT is valid or not.

if (isset($_POST["sessionToken"])) {
        if ($descopeSDK->verify($_POST["sessionToken"])) {
            $_SESSION["user"] = json_decode($_POST["userDetails"], true);
            $_SESSION["sessionToken"] = $_POST["sessionToken"];
            session_write_close();
    
            // User session validated and token saved
            exit();
        } else {
            error_log("Session token verification failed.");
            $descopeSDK->logout();
 
            // Redirect to login page
            exit();
        }
    } else {
        error_log("Session token is not set in POST request.");
 
        // Redirect to login page
        exit();
    }

Checkpoint

Your application is now integrated with Descope. Please test with sign-up or sign-in use case.

Need help?

Customize

Now that you have the end-to-end application working, you can choose to configure and personalize many different areas of Descope, including your brand, style, custom user authentication journeys, etc. We recommend starting with customizing your user-facing screens, such as signup and login.

Was this helpful?

On this page