Sign In with Email/Phone Number
Our React Native SDK offers the easiest way to integrate Cotter 's email/phone verification. You can simply call a function and it does most of the heavy lifting and authentication for you.
Concepts: Learn about how Sign in with Email/Phone Number works.

Overview

Verifying email and phone number in your mobile app using our React Native SDK consists of the following steps:
  1. 1.
    Call Cotter's Login function
  2. 2.
    Setup deep linking
  3. 3.
    Receive user's email or phone number, and whether or not it's verified

What you're building

Cotter's React Native SDK on Android and iOS

Steps

  1. 3.
    ​Setup deep linking: Cotter's authentication will redirect back to your application using a URL scheme.
  2. 4.
    ​Receive the Token: Include the returned OAuth token and email/phone number in your server

Step 1: Import Cotter as a dependency

Make sure you're using react-native version < 0.63
yarn
npm
1
yarn add react-native-cotter react-native-device-info rn-secure-storage react-native-randombytes react-native-camera react-native-svg react-native-securerandom buffer react-native-inappbrowser-reborn react-native-sha256
2
npx pod-install ios
Copied!
1
npm install --save react-native-cotter react-native-device-info rn-secure-storage react-native-randombytes react-native-camera react-native-svg react-native-securerandom buffer react-native-inappbrowser-reborn react-native-sha256
2
npx pod-install ios
Copied!
(Optional) Checkout additional steps for Android, React Native < 0.60, and Manual Installation.

Step 2: Signing Up or Logging In

Sign Up: Use the sign up method to:

  • Verify the user's email or phone number
  • Then create a new user in Cotter if successful
  • If you passed-in the email/phone into the function: if your user already exists, it will return an error "User already exists"
  • If you does not pass in the email/phone into the function: users can enter their email/phone in the pop-up browser, but it will NOT check if the user already exists. It will behave like the Log In method below.
Tip: Use the "Sign Up" method and pass in the user's email/phone to differentiate new and existing user. You can have an input text and collect the user's email/phone.

Log In: Use the login method to:

  • To authenticate a user based on their email.
  • If the user doesn't exist, this method will automatically create a new user.
Tip: Use the "Log In" method to login or register user on the same page
Using Email
Using Phone
1
import { Cotter } from 'react-native-cotter';
2
​
3
let cotter = new Cotter(API_KEY_ID); // your API_KEY_ID
4
await cotter.signUpWithEmailLink( // use Email & Magic Link
5
'myexample://auth_callback', // (setup later) URL Scheme for deep linking
6
(resp) => {console.log(resp)}, // Success Callback Function
7
(err) => {console.log(err)}, // Error Callback Function
8
{email: this.state.email}, // (Optional) , if you leave this blank, user can enter email in the in-app browser
9
);
Copied!

Sign Up

  • Magic Link: use cotter.signUpWithEmailLink
  • OTP: use cotter.signUpWithEmailOTP

Sign In

  • Magic Link: use cotter.signInWithEmailLink
  • OTP: use cotter.signInWithEmailOTP
If no email is specified, the user can enter the email in the in-app browser
1
import { Cotter } from 'react-native-cotter';
2
​
3
let cotter = new Cotter(API_KEY_ID); // your API_KEY_ID
4
await cotter.signUpWithPhoneLink( // use Phone & Magic Link
5
'myexample://auth_callback', // (setup later) URL Scheme for deep linking
6
(resp) => {console.log(resp)}, // Success Callback Function
7
(err) => {console.log(err)}, // Error Callback Function
8
{phone: this.state.phone, channel: "SMS" }, // (Optional), if you leave this blank, user can enter email in the in-app browser
9
);
Copied!

Sign Up

  • Magic Link: use cotter.signUpWithPhoneLink
  • OTP: use cotter.signUpWithPhoneOTP

Sign In

  • Magic Link: use cotter.signInWithPhoneLink
  • OTP: use cotter.signInWithPhoneOTP

Channels: (default to "SMS" if phone is specified)

  • To use SMS: {phone: this.state.phone, channel: "SMS"}
  • To use WhatsApp: {phone: this.state.phone, channel: "WHATSAPP"}
If no phone number is specified, the user can enter the phone number in the in-app browser and there will be buttons for WhatsApp and SMS available (based on your settings in the Dashboard > Branding).
To send code/link via SMS or WhatsApp, you'll need to add some balance to you project in the Dashboard.
Try this now! You should see an in-app browser looking like the image below popping up and ask you to authenticate.

Step 3: Setup Deep Linking

Pick a unique URL scheme for redirecting the user back to your app after the verification in the in-app browser is successful. For this example, we'll use myexample://auth_callback .
Make sure your URL scheme (the front part before ://) doesn't have an underscore or other special characters. To test it out, enter your Redirect URL here: https://jsfiddle.net/omd02jn5/​

Setup in Android

1
<activity
2
android:name=".MainActivity"
3
android:launchMode="singleTask"> <!-- Make launchMode to singleTask -->
4
5
<intent-filter>
6
<action android:name="android.intent.action.MAIN" />
7
<category android:name="android.intent.category.LAUNCHER" />
8
</intent-filter>
9
​
10
<!-- Setup Deep Linking Here -->
11
<intent-filter>
12
<action android:name="android.intent.action.VIEW" />
13
<category android:name="android.intent.category.DEFAULT" />
14
<category android:name="android.intent.category.BROWSABLE" />
15
<!-- This is for myexample://auth_callback -->
16
<!-- πŸ‘‡ Change this to your own URL scheme -->
17
<data android:scheme="myexample" android:host="auth_callback"/>
18
</intent-filter>
19
<!-- end -->
20
21
</activity>
Copied!

Setup in iOS

Add this in your ios/<YourAppName>/Info.plist​
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
<plist version="1.0">
4
<dict>
5
​
6
<!-- ADD THE LINES FROM HERE -->
7
<key>CFBundleURLTypes</key>
8
<array>
9
<dict>
10
<key>CFBundleTypeRole</key>
11
<string>Editor</string>
12
<key>CFBundleURLName</key>
13
<string>myexample</string> <!-- πŸ‘ˆ Change this to your own URL Scheme -->
14
<key>CFBundleURLSchemes</key>
15
<array>
16
<string>myexample</string> <!-- πŸ‘ˆ Change this to your own URL Scheme -->
17
</array>
18
</dict>
19
</array>
20
<!-- TO HERE -->
21
​
22
<key>CFBundleDevelopmentRegion</key>
23
<string>en</string>
Copied!
If you're targeting iOS 9.x or newer, add the following lines to YourApp/ios/YourApp/AppDelegate.m:
iOS 9.x or newer
1
// Add the header at the top of the file:
2
#import <React/RCTLinkingManager.h>
3
​
4
// Add this above `@end`:
5
- (BOOL)application:(UIApplication *)application
6
openURL:(NSURL *)url
7
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
8
{
9
return [RCTLinkingManager application:application openURL:url options:options];
10
}
Copied!
If you're targeting iOS 8.x or older, you can use the following code instead, add the following lines to YourApp/ios/YourApp/AppDelegate.m:
1
// Add the header at the top of the file:
2
#import <React/RCTLinkingManager.h>
3
​
4
// Add this above `@end`:
5
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
6
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
7
{
8
return [RCTLinkingManager application:application openURL:url
9
sourceApplication:sourceApplication annotation:annotation];
10
}
Copied!
If your app is using Universal Links, you'll need to add the following code as well, add the following lines to YourApp/ios/YourApp/AppDelegate.m:
1
// Add this above `@end`:
2
- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity
3
restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
4
{
5
return [RCTLinkingManager application:application
6
continueUserActivity:userActivity
7
restorationHandler:restorationHandler];
8
}
Copied!

Setup in React Native Project

React Navigation
React Navigation 5 or above
In your App.js
1
import { createStackNavigator } from 'react-navigation'
2
​
3
// Import Cotter's Loading Page
4
import { LoadingPage } from 'react-native-cotter';
5
6
const Main = createStackNavigator(
7
{
8
...
9
Register: { screen: Register },
10
11
// Redirect users Cotter's Handler page
12
CotterLoadingVerify: {
13
screen: LoadingPage, // Use Cotter's Loading Page
14
path: 'auth_callback' // Enable Deep linking redirection
15
},
16
17
}
18
)
Copied!
If you have Nested Stack Navigator, add path: '' to every parent stack.
1
// TARGET STACK
2
const RegisterStack = createStackNavigator(
3
{
4
Register: { screen: Register },
5
CotterLoadingVerify: {
6
screen: LoadingPage, // Use Cotter's Loading Page
7
path: 'auth_callback', // Enable Deep linking redirection
8
},
9
}
10
);
11
​
12
// PARENT 1
13
const RootStack = createStackNavigator(
14
{
15
// ADD path: '' here
16
RegisterStack: { screen: RegisterStack, path: '' },
17
...
18
}
19
);
20
​
21
// PARENT of PARENT 1
22
const RootSwitch = createSwitchNavigator(
23
{
24
Splash: { screen: Splash },
25
// ADD path: '' here
26
RootStack: { screen: RootStack, path: '' },
27
}
28
);
Copied!
If you're using the newer version of React Navigation, copy paste the code below to your App.js or index.js.
In your App.js or index.js
1
import { NavigationContainer, useLinking } from '@react-navigation/native';
2
​
3
function App() {
4
const ref = React.useRef();
5
​
6
const {getInitialState} = useLinking(ref, {
7
prefixes: ['https://myexample.cotter.app', 'myexample://'],
8
config: {
9
CotterLoadingVerify: 'auth_callback', // ADD THIS TO REDIRECT TO COTTER'S HANDLER PAGE
10
},
11
});
12
​
13
const [isReady, setIsReady] = React.useState(false);
14
const [initialState, setInitialState] = React.useState();
15
​
16
React.useEffect(() => {
17
Promise.race([
18
getInitialState(),
19
new Promise(resolve =>
20
// Timeout in 150ms if `getInitialState` doesn't resolve
21
// Workaround for https://github.com/facebook/react-native/issues/25675
22
setTimeout(resolve, 150)
23
),
24
])
25
.catch(e => {
26
console.error(e);
27
})
28
.then(state => {
29
if (state !== undefined) {
30
setInitialState(state);
31
}
32
​
33
setIsReady(true);
34
});
35
}, [getInitialState]);
36
​
37
if (!isReady) {
38
return null;
39
}
40
​
41
return (
42
<NavigationContainer initialState={initialState} ref={ref}>
43
{/* content πŸ‘ˆ */}
44
</NavigationContainer>
45
);
46
}
Copied!
In your Router
1
import {LoadingPage} from 'react-native-cotter';
2
​
3
function Router() {
4
return (
5
<Stack.Navigator>
6
...
7
8
// Add CotterLoadingVerify page
9
<Stack.Screen
10
name="CotterLoadingVerify"
11
component={LoadingPage}
12
options={{headerShown: false}}
13
/>
14
15
</Stack.Navigator>
16
);
17
}
Copied!
Remember to make sure your callbackURL in Step 2 is correct.
Try it again! You should see the in-app browser redirecting back after you've successfully verified.

Step 4: Receiving the Token in onSuccess or onError

onError

The onError function that you pass in will receive 2 parameters: errorMessage (string) and errorResponse (object). The errorResponse is an http response from attempt to verify the user's email/phone in Cotter's server.

onSuccess

The onSuccess function that you pass in will receive a response object that looks like this:
1
{
2
"identifier": {
3
"ID": "f4286df9-a923-429c-bc33-5089ffed5f68",
4
"created_at": "2020-07-21T22:53:21.211367Z",
5
"updated_at": "2020-07-21T22:53:21.211367Z",
6
"deleted_at": "0001-01-01T00:00:00Z",
7
"identifier": "[email protected]", // User's email
8
"identifier_type": "EMAIL",
9
"device_type": "BROWSER",
10
"device_name": "Mozilla/5.0 (Linux; Android 9; Android SDK built for x86 Build/PSR1.180720.075) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
11
"expiry": "2020-08-20T22:53:21.19705Z",
12
"timestamp": "2020-07-21T22:53:21.19705Z"
13
},
14
"oauth_token": {
15
"access_token": "eyJhbGciOiJFUz...", // Validate this access token
16
"id_token": "eyJhbGciOiJFUzI1...",
17
"refresh_token": "27944:lb31DY5pG229n...",
18
"expires_in": 3600,
19
"token_type": "Bearer",
20
"auth_method": "OTP"
21
},
22
"token": {...},
23
"user": {
24
"ID": "643a42c7-316a-4abe-b27e-f4d0f903bfea", // [Deprecated] Cotter uesr ID
25
"identifier": "[email protected]",
26
...
27
}
28
}
Copied!
Please use the identifier (email/phone number) as your main way to identify users, user.ID is deprecated.
This JSON object contains 3 objects, identifier , oauth_token and user .
  • The identifier object contains information about the user's email or phone number, device type and name, and expiry.
  • The oauth_token contains an access_token that you can validate in your backend.
  • The user contains the User object in Cotter, which includes a "Cotter User ID". You should associate your user with this Cotter User ID for reference.
You should include this JSON Object into your call to your backend for Login or Registration. Your backend should then verify that the access token is valid.​

Validating Cotter's Access Token

Checkout how to verify the OAuth Tokens from Cotter here:

πŸŽ‰ You're done!

Securing your Project

Since you'll be using your API Key from a front-end website or mobile app, your API_KEY_ID is exposed to anyone inspecting your code. Here are some ways to prevent abuse: