Facebook – Expo Documentation

Facebook

expo-facebook provides Facebook integration, such as logging in through Facebook, for React Native apps. Expo exposes a minimal native API since you can access Facebook’s

provides Facebook integration, such as logging in through Facebook, for React Native apps. Expo exposes a minimal native API since you can access Facebook’s Graph API directly through HTTP (using fetch , for example).

Platform Compatibility

Android DeviceAndroid EmulatoriOS DeviceiOS SimulatorWebStatus-success-iconStatus-success-iconStatus-success-iconStatus-success-iconStatus-failed-icon

Terminal

→ expo install expo-facebook

If you’re installing this in a bare React Native app, you should also follow these additional installation instructions.

💡

When following these steps you will find on the Facebook Developer site that there are many fields and steps that you don’t actually care about. Just look for the information that we ask you for and you will be OK!

appId option in your

Follow Facebook’s developer documentation to register an application with Facebook’s API and get an application ID. Take note of this application ID because it will be used as theoption in your Facebook.logInWithReadPermissionsAsync call.

Then follow these steps based on the platforms you’re targeting. This will need to be done from the Facebook developer site

Expo Go from the iOS App Store will use Expo’s own Facebook App ID. This is due to underlying configuration limitations, but the good news is it means less setup for you! The downside to this is that you can’t customize which permissions your app requests from Facebook (like user_photos or user_friends), or integrate Facebook login with other services like Firebase auth. If you need that functionality on iOS, you can build a standalone app. An easy way to test this is to

Expo Go from the Android Play Store will use the Facebook App ID that you provide, however, all Facebook API calls in the. This is due to underlying configuration limitations, but the good news is it means less setup for you! The downside to this is that you can’t customize which permissions your app requests from Facebook (likeor), or integrate Facebook login with other services like Firebase auth. If you need that functionality on iOS, you can build a standalone app. An easy way to test this is to run a simulator build and install the app in your simulator, or use expo-dev-client

Info-icon

You may have to switch the app from ‘development mode’ to ‘public mode’ on the Facebook developer page before other users can log in. This requires adding a privacy policy URL, which can be as simple as a GitHub Gist.

Add your app’s Bundle ID as a Bundle ID in the app settings page pictured below. An easy way to test that this is set up correctly is to run a simulator build

Triangle-down-icon

Screenshot of the Facebook developer page

  • Build your standalone app for Android.
  • Run eas credentials, select the profile that you would like to generate the SHA-1 Fingerprint for, and press return.
  • Take the resulting SHA1 Fingerprint and convert it to base64 (for example, using base64.guru). The resulting base64 string is your “Facebook Key Hash”.
  • Configure the Facebook Key Hash on the Facebook developer page pictured below.

Triangle-down-icon

Screenshot of the Facebook developer page

  • Add the field facebookScheme with your Facebook login redirect URL scheme found on the Facebook Developer website under “4. Configure Your info.plist.” It should look like "fb123456". If you do not do this, Facebook will not be able to redirect to your app after logging in.
  • Add the fields facebookAppId and facebookDisplayName, using your Facebook App ID and Facebook Display Name, respectively.
  • Optionally, add the following fields:
    • facebookAutoLogAppEventsEnabled, defaults to Facebook’s default policy (Only applies to standalone apps)
    • facebookAdvertiserIDCollectionEnabled, defaults to Facebook’s default policy (Only applies to standalone apps)

expo-facebook using its built-in expo run:[android|ios]). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect.

You can also configureusing its built-in config plugin if you use config plugins in your project ( EAS Build or). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect.

Triangle-down-icon

Are you using this library in a bare React Native app?

Learn how to configure the native projects in the installation instructions in the expo-facebook repository

{

"expo"

:

{

"plugins"

:

[

[

"expo-facebook"

,

{

"userTrackingPermission"

:

false

}

]

]

}

}

NameDefaultDescriptionuserTrackingPermission"This identifier will be used to deliver personalized ads to you."Only for:  

Apple-icon

iOS

A string to set the NSUserTrackingUsageDescription permission message, or set to the boolean value false to omit the field entirely.

async

function

logIn

(

)

{

try

{

await

Facebook

.

initializeAsync

(

{

appId

:

'<APP_ID>'

,

}

)

;

const

{

type

,

token

,

expirationDate

,

permissions

,

declinedPermissions

}

=

await

Facebook

.

logInWithReadPermissionsAsync

(

{

permissions

:

[

'public_profile'

]

,

}

)

;

if

(

type

===

'success'

)

{

const

response

=

await

fetch

(

`

https://graph.facebook.com/me?access_token=

${

token

}

`

)

;

Alert

.

alert

(

'Logged in!'

,

`

Hi

${

(

await

response

.

json

(

)

)

.

name

}

!

`

)

;

}

else

{

}

}

catch

(

{

message

}

)

{

alert

(

`

Facebook Login Error:

${

message

}

`

)

;

}

}

import

*

as

Facebook

from

'expo-facebook'

;

usePermissions

NameTypeDescriptionoptions

(optional)

PermissionHookOptions<

object

>

Check or request permissions to use data tracking.
This uses both requestPermissionsAsync and getPermissionsAsync to interact with the permissions.

Example

const

[

status

,

requestPermission

]

=

Facebook

.

usePermissions

(

)

;

Returns

  • Undo-icon[

    null |

    PermissionResponsePermissionResponse

    RequestPermissionMethod <> ,

    PermissionResponse

    GetPermissionMethod

flushAsync()

Explicitly kicks off flushing of events to Facebook.

Returns

  • Undo-iconPromise<

    void

    >

getAdvertiserIDAsync()

Get the advertiser ID from Facebook.

Returns

  • Undo-iconPromise<

    string |

    null

    >

A promise fulfilled with the advertiser id or null if not set.

getAnonymousIDAsync()

Get an anonymous ID from Facebook.

Returns

  • Undo-iconPromise<

    string |

    null

    >

A promise fulfilled with an anonymous id or null if not set.

Only for:  

Android-icon

Android

getAttributionIDAsync()

Gets the attribution ID from Facebook.

Returns

  • Undo-iconPromise<

    string |

    null

    >

A promise fulfilled with the attribution id or null if not set.

getAuthenticationCredentialAsync()

Returns the FacebookAuthenticationCredential object if a user is authenticated, and null if no valid authentication exists.

You can use this method to check if the user should sign in or not.

Returns

  • Undo-iconPromise<FacebookAuthenticationCredential |

    null

getPermissionsAsync()

Checks application’s permissions for using data for tracking the user or the device.

Info-icon

iOS: it requires the NSUserTrackingUsageDescription message added to the info.plist.

Returns

  • Undo-iconPromise<PermissionResponse

A promise that resolves to an object of type PermissionResponse.

getUserIDAsync()

Gets the user ID.

Returns

  • Undo-iconPromise<

    string |

    null

    >

A promise fulfilled with the user id or null if not set.

initializeAsync(optionsOrAppId, appName)

NameTypeDescriptionoptionsOrAppId

string |

FacebookInitializationOptionsappName

(optional)

string

Calling this method ensures that the SDK is initialized.
You have to call this method before calling any method that uses
the FBSDK (ex: logInWithReadPermissionsAsync, logOutAsync) to ensure that
Facebook support is initialized properly.

  • On Android and iOS you can optionally provide an appId argument.
    • If you don’t provide appId, the Facebook SDK will try to use appId from native app resources (which in standalone apps you define in app.json, in app store development clients are unavailable, and in bare apps you configure yourself according to Facebook’s setup documentation for iOS and Android). If the Facebook SDK fails to find an appId value, the returned promise will be rejected.
    • The same resolution mechanism works for appName.
  • If you provide an explicit appId, it will override any other source.

Returns

  • Undo-iconPromise<

    void

    >

logEventAsync(eventName, parameters)

NameTypeDescriptioneventNamestringparameters

(optional)

Params

Logs an event with eventName and optional parameters. Supports the optional parameter valueToSum,
which when reported, all of the valueToSum properties are summed together. For example, if 10 people purchased
one item and each item cost $10 (and passed in valueToSum) then they would be added together to report $100.
Parameters must be either strings or numbers, otherwise no event will be logged.

To view and test app events, please visit Facebook’s Event Manager- https://www.facebook.com/events_manager2/list/app/

Returns

  • Undo-iconPromise<

    void

    >

logInWithReadPermissionsAsync(options)

NameTypeDescriptionoptions

(optional)

FacebookOptions

A map of options:

  • permissions (array) — An array specifying the permissions to ask for from Facebook for this login. The permissions are strings as specified in the Facebook API documentation. The default permissions are [‘public_profile’, ’email’].

Default: {}

Prompts the user to log into Facebook and grants your app permission to access their Facebook data. On iOS and Android, if the Facebook app isn’t installed then a web view will be used to authenticate.

Returns

  • Undo-iconPromise<FacebookLoginResult

If the user or Facebook cancelled the login, returns { type: ‘cancel’ }. Otherwise, returns { type: ‘success’ } & FacebookAuthenticationCredential.

logOutAsync()

Logs out of the currently authenticated session.

Returns

  • Undo-iconPromise<

    void

    >

logPurchaseAsync(purchaseAmount, currencyCode, parameters)

NameTypeDescriptionpurchaseAmountnumbercurrencyCodestringparameters

(optional)

Params

Logs a purchase event with the amount, currency code, and optional parameters.
Parameters must be either strings or numbers, otherwise no event will be logged.
See http://en.wikipedia.org/wiki/ISO_4217 for currencyCodes.

Returns

  • Undo-iconPromise<

    void

    >

logPushNotificationOpenAsync(campaign)

NameTypeDescriptioncampaignstring

Logs an app event that tracks that the application was opened via Push Notification. Accepts
a string describing the campaign of the Push Notification.

Returns

  • Undo-iconPromise<

    void

    >

requestPermissionsAsync()

Asks for permissions to use data for tracking the user or the device.

Info-icon

iOS: it requires the NSUserTrackingUsageDescription message added to the info.plist.

Returns

  • Undo-iconPromise<PermissionResponse

A promise that resolves to an object of type PermissionResponse.

setAdvertiserIDCollectionEnabledAsync(enabled)

NameTypeDescriptionenabledboolean

Whether advertiser-id should be collected

Whether the Facebook SDK should collect advertiser ID properties, like the Apple IDFA
and Android Advertising ID, automatically. Advertiser IDs let you identify and target specific customers.
To learn more visit Facebook documentation
describing that topic.

In some cases, you may want to disable or delay the collection of advertiser-id,
such as to obtain user consent or fulfill legal obligations.

This method corresponds to this
and this native SDK methods.

Returns

  • Undo-iconPromise<

    void

    >

setAdvertiserTrackingEnabledAsync(enabled)

NameTypeDescriptionenabledboolean

Whether advertising tracking of the Facebook SDK should be enabled

Sets whether Facebook SDK should enable advertising tracking,
(more info here).

Limitations:

  1. AdvertiserTrackingEnabled is only available for iOS 14+.
  2. For iOS 13 or earlier, AdvertiserTrackingEnabled uses the Limit Ad Tracking setting as its value.

This method corresponds to this

Returns

  • Undo-iconPromise<

    boolean

    >

Whether the value is set successfully. It will always return false in Android, iOS 13 and below.

Warning-icon

Deprecated. Explicitly call initializeAsync instead.

setAutoInitEnabledAsync(enabled)

NameTypeDescriptionenabledboolean

Returns

  • Undo-iconPromise<

    void

    >

setAutoLogAppEventsEnabledAsync(enabled)

NameTypeDescriptionenabledboolean

Whether automatic events logging of the Facebook SDK should be enabled

Sets whether Facebook SDK should log app events. App events involve eg. app installs,
app launches (more info here
and here).

In some cases, you may want to disable or delay the collection of automatically logged events,
such as to obtain user consent or fulfill legal obligations.

This method corresponds to this
and this native SDK methods.

Returns

  • Undo-iconPromise<

    void

    >

setUserDataAsync(userData)

NameTypeDescriptionuserDataUserData

Sets additional data about the user to increase the chances of matching a Facebook user.

Returns

  • Undo-iconPromise<

    void

    >

setUserIDAsync(userID)

NameTypeDescriptionuserID

null |

string

Sets a custom user ID to associate with all app events.
The userID is persisted until it is cleared by passing nil.

Returns

  • Undo-iconPromise<

    void

    >

PermissionResponse

PermissionResponse Properties

NameTypeDescriptioncanAskAgainbooleanexpiresPermissionExpirationgrantedbooleanstatusPermissionStatus

FacebookAuthenticationCredential

NameTypeDescriptionappIdstring

Application ID used to initialize the Facebook SDK app.

dataAccessExpirationDateDate

Time at which the current user data access expires.

declinedPermissions

(optional)

string[]

List of requested permissions that the user has declined.

expirationDateDate

Time at which the token expires.

expiredPermissions

(optional)

string[]

List of permissions that were expired with this access token.

graphDomain

(optional)

string

A website domain within the Graph API.

Info-icon

See:

https://developers.facebook.com/docs/graph-api/reference/v5.0/domain

permissions

(optional)

string[]

List of granted permissions.

refreshDate

(optional)

Date

The last time the token was refreshed (or when it was first obtained).

signedRequest

(optional)

string

A valid raw signed request as a string.

tokenstring

Access token for the authenticated session. This token provides access to the Facebook Graph API.

tokenSource

(optional)

stringOnly for:  

Android-icon

Android

Indicates how this token was obtained.

userIdstring

App-scoped Facebook ID of the user.

FacebookInitializationOptions

Acceptable values are: FacebookSDKScriptURLOptions, FacebookSDKInitializationOptions, FacebookNativeInitializationOptions.

FacebookLoginResult

NameTypeDescriptiontype'cancel'

FacebookNativeInitializationOptions

NameTypeDescriptionappName

(optional)

string

An optional Facebook App Name argument for iOS and Android.

FacebookOptions

NameTypeDescriptionpermissions

(optional)

string[]

FacebookSDKInitializationOptions

NameTypeDescriptionappId

(optional)

string

Application ID used to initialize the FBSDK app.

appId from Android and iOS.
app resources (which in standalone apps you would define in app.json, in the Expo client are unavailable,
and in bare you configure yourself according to Facebook setup documentation
for

On Android and iOS if you don’t provide this, Facebook SDK will try to usefrom Android and iOS. app resources (which in standalone apps you would define in, in the Expo client are unavailable, and in bare you configure yourself according to Facebook setup documentation for iOS and Android ). If it fails to find one, the promise will be rejected.

autoLogAppEvents

(optional)

boolean

Sets whether Facebook SDK should log app events. App events involve app eg. installs, app launches (more info here and here ). In some cases, you may want to disable or delay the collection of automatically logged events, such as to obtain user consent or fulfill legal obligations.

This method corresponds to:

  • iOS disable auto events
  • Android disable auto events

version

(optional)

string

Selects the version of FBSDK to use.

Info-icon

See: Graph API Initialization

FacebookSDKScriptURLOptions

NameTypeDescriptiondomain

(optional)

stringOnly for:  

Android-icon

Android

Sets the base Facebook domain to use when making network requests.

Default: 'connect.facebook.net'

PermissionExpiration

Acceptable values are: 'never', number.

PermissionHookOptions

Acceptable values are: PermissionHookBehavior, Options.

UserData

Info about a user to increase chances of matching a Facebook user.
See https://developers.facebook.com/docs/app-events/advanced-matching for
more info about the expected format of each field.

NameTypeDescriptioncity

(optional)

stringcountry

(optional)

stringdateOfBirth

(optional)

stringemail

(optional)

stringfirstName

(optional)

stringgender

(optional)

'm' |

'f'

lastName

(optional)

stringphone

(optional)

stringstate

(optional)

stringzip

(optional)

string

PermissionStatus

DENIED

PermissionStatus . DENIED = "denied"

GRANTED

PermissionStatus . GRANTED = "granted"

UNDETERMINED

PermissionStatus . UNDETERMINED = "undetermined"

Attempted to use the Facebook SDK before it was initialized. Ensure initializeAsync has successfully resolved before attempting to use the Facebook SDK.

Failed to initialize the Facebook SDK app because the appId option wasn’t provided and the appId couldn’t be resolved automatically from the native configuration files.

An error occurred while trying to log in to Facebook.

fetch API to get info about the user from the

You can use theAPI to get info about the user from the Facebook Graph API . Here are some helper methods you can use to make data access easier.

 

async

function

getUserAsync

(

)

{

const

{

name

}

=

await

requestAsync

(

'me'

)

;

console

.

log

(

`

Hello

${

name

}

👋

`

)

;

}

async

function

requestAsync

(

path

:

string

,

token

?

:

string

)

:

Promise

<

any

>

{

let

resolvedToken

=

token

;

if

(

!

token

)

{

const

auth

=

await

Facebook

.

getAuthenticationCredentialAsync

(

)

;

if

(

!

auth

)

{

throw

new

Error

(

'User is not authenticated. Ensure `logInWithReadPermissionsAsync` has successfully resolved before attempting to use the FBSDK Graph API.'

)

;

}

resolvedToken

=

auth

.

token

;

}

const

response

=

await

fetch

(

`

https://graph.facebook.com/

${

path

}

?access_token=

${

encodeURIComponent

(

resolvedToken

)

}

`

)

;

const

body

=

await

response

.

json

(

)

;

return

body

;

}