useNylasConnect is the main hook of the Nylas Connect React library. It manages authentication state information and includes methods for connecting and disconnecting users.
import React from "react";import { useNylasConnect, UseNylasConnectConfig } from "@nylas/react/connect";
const config: UseNylasConnectConfig = { clientId: "<NYLAS_CLIENT_ID>", redirectUri: "http://localhost:3000/auth/callback",};
function App() { const { isConnected, grant, connect, logout, isLoading, error } = useNylasConnect(config);
// Show loading state while initializing if (isLoading) { return <div>Loading...</div>; }
// Show error state if something went wrong if (error) { return ( <div> <h3>Authentication Error</h3> <p>{error.message}</p> <button onClick={() => window.location.reload()}> Retry </button> </div> ); }
// Render authenticated state if (isConnected && grant) { return ( <div> <h2>Connected!</h2> <p>Welcome, {grant.name || grant.email}</p> {grant.picture && <img src={grant.picture} alt="Profile" />}
<div> <p><strong>Provider:</strong> {grant.provider}</p> <p><strong>Email:</strong> {grant.email}</p> {grant.emailVerified && <p>✓ Email verified</p>} </div>
<button onClick={async () => { try { await logout(); } catch (e) { console.error("Logout failed", e); } }} > Logout </button> </div> ); }
// Render unauthenticated state return ( <div> <h1>Connect Your Email</h1> <p>Connect your email account to get started with Nylas.</p>
<button onClick={async () => { try { await connect({ method: "popup" }); } catch (e) { console.error("Connect failed", e); } }} > Connect with Popup </button>
<button onClick={async () => { try { await connect({ method: "inline" }); } catch (e) { console.error("Connect failed", e); } }} > Connect with Redirect </button> </div> );}UseNylasConnectConfig properties
Section titled “UseNylasConnectConfig properties”The UseNylasConnectConfig extends ConnectConfig from @nylas/connect, which means all base configuration options are available. Below are the properties specific to the React hook, as well as inherited properties from the core library.
apiUrl
Section titled “apiUrl”| Name | apiUrl |
| Description | The Nylas API base URL. |
| Type | https://api.us.nylas.com | https://api.eu.nylas.com |
| Default | https://api.us.nylas.com |
autoHandleCallback
Section titled “autoHandleCallback”| Name | autoHandleCallback |
| Description | When true, automatically processes OAuth callbacks when the component mounts. Set to false if you want to manually handle callbacks. |
| Type | boolean |
| Default | true |
autoRefreshInterval
Section titled “autoRefreshInterval”| Name | autoRefreshInterval |
| Description | Auto-refresh session interval in milliseconds. When set, the hook automatically checks and updates the session at this interval. Set to 0 or undefined to disable. |
| Type | number |
clientId
Section titled “clientId”| Name | clientId |
| Description | Your Nylas application’s client ID. |
| Type | string | NYLAS_CLIENT_ID |
codeExchange
Section titled “codeExchange”| Name | codeExchange |
| Description | Optional custom code exchange method. When provided, it replaces the built-in token exchange and allows you to handle the OAuth code exchange on your backend for enhanced security. |
| Type | CodeExchangeMethod |
| Name | debug |
| Description | When true, enables logging for debugging purposes and overrides logLevel. This is true by default on localhost. |
| Type | boolean |
defaultScopes
Section titled “defaultScopes”| Name | defaultScopes |
| Description | The default set of scopes Nylas Connect requests from the provider. Can be a simple array or a provider-specific object (ProviderScopes) that lets you set different scopes for each provider. |
| Type | NylasScope[] | ProviderScopes |
enableAutoRecovery
Section titled “enableAutoRecovery”| Name | enableAutoRecovery |
| Description | When true, enables automatic error recovery for network errors during auto-refresh. Failed refresh attempts will be retried at the next interval instead of setting an error state. |
| Type | boolean |
| Default | false |
environment
Section titled “environment”| Name | environment |
| Description | Your Nylas application’s environment. The Connect React library automatically detects this based on the hostname and NODE_ENV. |
| Type | development | production | staging |
identityProviderToken
Section titled “identityProviderToken”| Name | identityProviderToken |
| Description | Optional callback to provide an external identity provider JWT token for idp_claims parameter during token exchange. Used for integrating external identity providers via JWKS. Return null to skip or throw an error to fail authentication. |
| Type | IdentityProviderTokenCallback |
initialLoadingState
Section titled “initialLoadingState”| Name | initialLoadingState |
| Description | Sets the initial loading state when the hook mounts. When true, the hook starts in a loading state while checking for existing sessions. |
| Type | boolean |
| Default | true |
logLevel
Section titled “logLevel”| Name | logLevel |
| Description | The verbosity level for log messages. Set to off to disable log messages. |
| Type | debug | error | info | off | warn |
persistTokens
Section titled “persistTokens”| Name | persistTokens |
| Description | When true, the Connect React library persists tokens and grant information in localStorage. When false, this information is stored in local memory only. |
| Type | boolean |
| Default | true |
redirectUri
Section titled “redirectUri”| Name | redirectUri |
| Description | The OAuth redirect URI. This value must match your application configuration in the Nylas Dashboard. |
| Type | string | NYLAS_REDIRECT_URI |
retryAttempts
Section titled “retryAttempts”| Name | retryAttempts |
| Description | Number of retry attempts for failed operations like connect(), logout(), and refreshSession(). Uses exponential backoff between retries. |
| Type | number |
| Default | 0 |
Methods
Section titled “Methods”connect()
Section titled “connect()”| Method | connect() |
| Description | Starts the OAuth authentication flow. Call this method directly in a user gesture when using the pop-up method. |
| Type | (options?: ConnectOptions) => Promise<ConnectResult | string> |
logout()
Section titled “logout()”| Method | logout() |
| Description | Signs the current user out of their session and clears stored authentication data. |
| Type | (grantId?: string) => Promise<void> |
refreshSession()
Section titled “refreshSession()”| Method | refreshSession() |
| Description | Manually refreshes the current session state by checking the connection status and updating grant information. |
| Type | () => Promise<void> |
subscribe()
Section titled “subscribe()”| Method | subscribe() |
| Description | Subscribes to authentication state changes. This method returns an unsubscribe function to remove the listener. |
| Type | (callback: ConnectStateChangeCallback) => () => void |
Additional properties
Section titled “Additional properties”connectClient
Section titled “connectClient”| Name | connectClient |
| Description | Provides access to the underlying NylasConnect client instance. You can use this to call methods like callback(), getAuthUrl(), or access lower-level functionality. |
| Type | NylasConnect |
setLogLevel
Section titled “setLogLevel”| Name | setLogLevel |
| Description | Set the verbosity level for log messages. |
| Type | (level: LogLevel) => void |
Return values
Section titled “Return values”useNylasConnect returns an object (UseNylasConnectReturn) containing state properties, action methods, and the underlying client instance.
State Properties
Section titled “State Properties”| Property | Type | Description |
|---|---|---|
error | Error | null | An object containing information about the last error encountered during authentication. |
grant | GrantInfo | null | An object containing information about the currently authenticated grant. |
isConnected | boolean | The current connection state. When true, indicates that the user is authenticated. |
isLoading | boolean | The current loading state. When true, indicates that an authentication operation is in progress. |
Action Methods
Section titled “Action Methods”| Property | Type | Description |
|---|---|---|
connect | (options?: ConnectOptions) => Promise<ConnectResult | string> | Starts the OAuth authentication flow. See Methods section for details. |
logout | (grantId?: string) => Promise<void> | Signs the current user out and clears stored authentication data. See Methods section for details. |
refreshSession | () => Promise<void> | Manually refreshes the current session state. See Methods section for details. |
subscribe | (callback: ConnectStateChangeCallback) => () => void | Subscribes to authentication state changes. See Methods section for details. |
setLogLevel | (level: LogLevel | "off") => void | Sets the verbosity level for log messages. See Additional properties section for details. |
Client Instance
Section titled “Client Instance”| Property | Type | Description |
|---|---|---|
connectClient | NylasConnect | Provides access to the underlying NylasConnect client instance. See Additional properties section for details. |