Skip to content

useNylasConnect

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>
);
}

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.

NameapiUrl
DescriptionThe Nylas API base URL.
Typehttps://api.us.nylas.com | https://api.eu.nylas.com
Defaulthttps://api.us.nylas.com
NameautoHandleCallback
DescriptionWhen true, automatically processes OAuth callbacks when the component mounts. Set to false if you want to manually handle callbacks.
Typeboolean
Defaulttrue
NameautoRefreshInterval
DescriptionAuto-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.
Typenumber
NameclientId
DescriptionYour Nylas application’s client ID.
Typestring | NYLAS_CLIENT_ID
NamecodeExchange
DescriptionOptional 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.
TypeCodeExchangeMethod
Namedebug
DescriptionWhen true, enables logging for debugging purposes and overrides logLevel. This is true by default on localhost.
Typeboolean
NamedefaultScopes
DescriptionThe 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.
TypeNylasScope[] | ProviderScopes
NameenableAutoRecovery
DescriptionWhen 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.
Typeboolean
Defaultfalse
Nameenvironment
DescriptionYour Nylas application’s environment. The Connect React library automatically detects this based on the hostname and NODE_ENV.
Typedevelopment | production | staging
NameidentityProviderToken
DescriptionOptional 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.
TypeIdentityProviderTokenCallback
NameinitialLoadingState
DescriptionSets the initial loading state when the hook mounts. When true, the hook starts in a loading state while checking for existing sessions.
Typeboolean
Defaulttrue
NamelogLevel
DescriptionThe verbosity level for log messages. Set to off to disable log messages.
Typedebug | error | info | off | warn
NamepersistTokens
DescriptionWhen true, the Connect React library persists tokens and grant information in localStorage. When false, this information is stored in local memory only.
Typeboolean
Defaulttrue
NameredirectUri
DescriptionThe OAuth redirect URI. This value must match your application configuration in the Nylas Dashboard.
Typestring | NYLAS_REDIRECT_URI
NameretryAttempts
DescriptionNumber of retry attempts for failed operations like connect(), logout(), and refreshSession(). Uses exponential backoff between retries.
Typenumber
Default0
Methodconnect()
DescriptionStarts the OAuth authentication flow. Call this method directly in a user gesture when using the pop-up method.
Type(options?: ConnectOptions) => Promise<ConnectResult | string>
Methodlogout()
DescriptionSigns the current user out of their session and clears stored authentication data.
Type(grantId?: string) => Promise<void>
MethodrefreshSession()
DescriptionManually refreshes the current session state by checking the connection status and updating grant information.
Type() => Promise<void>
Methodsubscribe()
DescriptionSubscribes to authentication state changes. This method returns an unsubscribe function to remove the listener.
Type(callback: ConnectStateChangeCallback) => () => void
NameconnectClient
DescriptionProvides access to the underlying NylasConnect client instance. You can use this to call methods like callback(), getAuthUrl(), or access lower-level functionality.
TypeNylasConnect
NamesetLogLevel
DescriptionSet the verbosity level for log messages.
Type(level: LogLevel) => void

useNylasConnect returns an object (UseNylasConnectReturn) containing state properties, action methods, and the underlying client instance.

PropertyTypeDescription
errorError | nullAn object containing information about the last error encountered during authentication.
grantGrantInfo | nullAn object containing information about the currently authenticated grant.
isConnectedbooleanThe current connection state. When true, indicates that the user is authenticated.
isLoadingbooleanThe current loading state. When true, indicates that an authentication operation is in progress.
PropertyTypeDescription
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) => () => voidSubscribes to authentication state changes. See Methods section for details.
setLogLevel(level: LogLevel | "off") => voidSets the verbosity level for log messages. See Additional properties section for details.
PropertyTypeDescription
connectClientNylasConnectProvides access to the underlying NylasConnect client instance. See Additional properties section for details.