You can integrate external identity providers (IDPs) with the Nylas Connect React library to authenticate users through your existing identity system. This guide shows you how to use the useNylasConnect hook with popular React-based identity providers.
Before you begin
Section titled “Before you begin”Before implementing external IDP integration, you need to configure two things:
-
Nylas Dashboard Settings: Configure allowed origins and callback URIs in your Nylas Dashboard IDP settings.
-
Provider Configuration: Set up callback URLs and origins in your identity provider’s dashboard.
For detailed setup instructions for each provider, see the Before you begin section in the vanilla guide.
How it works
Section titled “How it works”The React integration follows the same authentication flow as the vanilla version, but uses React hooks and context providers:
- Wrap your app with the IDP’s React provider (e.g.,
Auth0Provider,ClerkProvider) - Use the IDP’s React hooks to get access tokens
- Pass the token to
useNylasConnectvia theidentityProviderTokenconfig - Use the
connectmethod fromuseNylasConnectto link the user’s email account
Auth0 integration
Section titled “Auth0 integration”Auth0 provides a React SDK that integrates seamlessly with the Nylas Connect React library.
For Auth0 configuration steps, see the Auth0 setup guide.
Install the required packages:
npm install @auth0/auth0-react @nylas/reactImplementation
Section titled “Implementation”import { Auth0Provider, useAuth0 } from '@auth0/auth0-react';import { useNylasConnect } from '@nylas/react/connect';import { useEffect, useState } from 'react';
function Auth0Content() { const { isAuthenticated, getAccessTokenSilently, loginWithPopup, logout, user } = useAuth0();
// Configure Nylas Connect with Auth0 token const { isConnected, connect, logout: disconnectEmail } = useNylasConnect({ clientId: "<NYLAS_CLIENT_ID>", redirectUri: window.location.origin + "/auth/callback", identityProviderToken: async () => { try { const token = await getAccessTokenSilently(); return token; } catch { return null; } } });
return ( <div> {/* Auth0 Login */} {!isAuthenticated ? ( <button onClick={() => loginWithPopup()}> Log in with Auth0 </button> ) : ( <div> <p>Logged in as: {user?.email}</p> <button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}> Log out </button> </div> )}
{/* Nylas Email Connection */} {isAuthenticated && !isConnected && ( <button onClick={() => connect({ method: 'popup' })}> Connect your inbox </button> )}
{isConnected && ( <div> <p>✓ Email inbox connected</p> <button onClick={() => disconnectEmail()}> Disconnect </button> </div> )} </div> );}
export default function App() { return ( <Auth0Provider domain="<AUTH0_DOMAIN>" clientId="<AUTH0_CLIENT_ID>" authorizationParams={{ redirect_uri: window.location.origin }} > <Auth0Content /> </Auth0Provider> );}Making API calls
Section titled “Making API calls”Extract the user ID from the Auth0 token and use it to make Nylas API calls:
function EmailList() { const { getAccessTokenSilently } = useAuth0(); const [emails, setEmails] = useState([]);
useEffect(() => { const fetchEmails = async () => { const token = await getAccessTokenSilently();
// Parse user ID from JWT const payload = JSON.parse(atob(token.split('.')[1])); const userId = payload.sub;
const response = await fetch('https://api.us.nylas.com/v3/grants/me/messages', { headers: { 'Authorization': `Bearer ${token}`, 'X-Nylas-External-User-Id': userId } });
const data = await response.json(); setEmails(data.data); };
fetchEmails(); }, [getAccessTokenSilently]);
return <div>{/* Render emails */}</div>;}Clerk integration
Section titled “Clerk integration”Clerk provides prebuilt React components and hooks for authentication.
For Clerk configuration steps, see the Clerk setup guide.
Install the required packages:
npm install @clerk/clerk-react @nylas/reactImplementation
Section titled “Implementation”import { ClerkProvider, SignedIn, SignedOut, SignInButton, useAuth, useClerk, useUser } from '@clerk/clerk-react';import { useNylasConnect } from '@nylas/react/connect';
function ClerkContent() { const { isSignedIn, getToken } = useAuth(); const { signOut } = useClerk(); const { user } = useUser();
// Configure Nylas Connect with Clerk token const { isConnected, connect, logout: disconnectEmail } = useNylasConnect({ clientId: "<NYLAS_CLIENT_ID>", redirectUri: window.location.origin + "/auth/callback", identityProviderToken: async () => { try { const token = await getToken(); return token; } catch { return null; } } });
return ( <div> {/* Clerk Login */} <SignedOut> <SignInButton mode="modal"> <button>Log in with Clerk</button> </SignInButton> </SignedOut>
<SignedIn> <div> <p>Logged in as: {user?.primaryEmailAddress?.emailAddress}</p> <button onClick={() => signOut()}>Log out</button> </div>
{/* Nylas Email Connection */} {!isConnected ? ( <button onClick={() => connect({ method: 'popup' })}> Connect your inbox </button> ) : ( <div> <p>✓ Email inbox connected</p> <button onClick={() => disconnectEmail()}> Disconnect </button> </div> )} </SignedIn> </div> );}
export default function App() { return ( <ClerkProvider publishableKey="<CLERK_PUBLISHABLE_KEY>"> <ClerkContent /> </ClerkProvider> );}Making API calls
Section titled “Making API calls”function EmailList() { const { getToken } = useAuth(); const [emails, setEmails] = useState([]);
useEffect(() => { const fetchEmails = async () => { const token = await getToken();
// Parse user ID from JWT const payload = JSON.parse(atob(token.split('.')[1])); const userId = payload.sub;
const response = await fetch('https://api.us.nylas.com/v3/grants/me/messages', { headers: { 'Authorization': `Bearer ${token}`, 'X-Nylas-External-User-Id': userId } });
const data = await response.json(); setEmails(data.data); };
if (token) fetchEmails(); }, [getToken]);
return <div>{/* Render emails */}</div>;}Google Identity integration
Section titled “Google Identity integration”Google Identity Services can be integrated with React using the @react-oauth/google package.
For Google Cloud configuration steps, see the Google setup guide.
Install the required packages:
npm install @react-oauth/google @nylas/reactImplementation
Section titled “Implementation”import { GoogleOAuthProvider, GoogleLogin, googleLogout } from '@react-oauth/google';import { useNylasConnect } from '@nylas/react/connect';import { useState } from 'react';
function GoogleContent() { const [credential, setCredential] = useState<string | null>(null); const [profile, setProfile] = useState<any>(null);
// Configure Nylas Connect with Google token const { isConnected, connect, logout: disconnectEmail } = useNylasConnect({ clientId: "<NYLAS_CLIENT_ID>", redirectUri: window.location.origin + "/auth/callback", provider: "google", identityProviderToken: async () => credential });
const handleGoogleSuccess = (response: any) => { setCredential(response.credential);
// Parse user info from JWT const payload = JSON.parse(atob(response.credential.split('.')[1])); setProfile({ name: payload.name, email: payload.email }); };
const handleLogout = () => { googleLogout(); setCredential(null); setProfile(null); };
return ( <div> {/* Google Login */} {!profile ? ( <GoogleLogin onSuccess={handleGoogleSuccess} onError={() => console.error('Login failed')} /> ) : ( <div> <p>Logged in as: {profile.email}</p> <button onClick={handleLogout}>Log out</button> </div> )}
{/* Nylas Email Connection */} {profile && !isConnected && ( <button onClick={() => connect({ method: 'popup' })}> Connect your inbox </button> )}
{isConnected && ( <div> <p>✓ Email inbox connected</p> <button onClick={() => disconnectEmail()}> Disconnect </button> </div> )} </div> );}
export default function App() { return ( <GoogleOAuthProvider clientId="<GOOGLE_CLIENT_ID>"> <GoogleContent /> </GoogleOAuthProvider> );}WorkOS integration
Section titled “WorkOS integration”WorkOS provides enterprise authentication with React support through AuthKit.
For WorkOS configuration steps, see the WorkOS setup guide.
Install the required packages:
npm install @workos-inc/authkit-react @nylas/reactImplementation
Section titled “Implementation”import { AuthKitProvider, useAuth } from '@workos-inc/authkit-react';import { useNylasConnect } from '@nylas/react/connect';
function WorkOSContent() { const { user, isLoading, signIn, signOut } = useAuth();
// Configure Nylas Connect with WorkOS token const { isConnected, connect, logout: disconnectEmail } = useNylasConnect({ clientId: "<NYLAS_CLIENT_ID>", redirectUri: window.location.origin + "/auth/callback", identityProviderToken: async () => { try { // WorkOS provides the token through the auth context const token = await user?.getToken(); return token || null; } catch { return null; } } });
if (isLoading) { return <div>Loading...</div>; }
return ( <div> {/* WorkOS Login */} {!user ? ( <button onClick={() => signIn()}> Log in with WorkOS </button> ) : ( <div> <p>Logged in as: {user.email}</p> <button onClick={() => signOut()}>Log out</button> </div> )}
{/* Nylas Email Connection */} {user && !isConnected && ( <button onClick={() => connect({ method: 'popup' })}> Connect your inbox </button> )}
{isConnected && ( <div> <p>✓ Email inbox connected</p> <button onClick={() => disconnectEmail()}> Disconnect </button> </div> )} </div> );}
export default function App() { return ( <AuthKitProvider clientId="<WORKOS_CLIENT_ID>" redirectUri={window.location.origin} > <WorkOSContent /> </AuthKitProvider> );}useNylasConnect hook reference
Section titled “useNylasConnect hook reference”The useNylasConnect hook returns the following properties and methods:
const { isConnected, // Boolean: Whether email is connected connect, // Function: Start email connection flow logout, // Function: Disconnect email account session, // Object: Current session data getConnectionStatus, // Function: Check connection status refreshSession // Function: Refresh session data} = useNylasConnect(config);For complete hook documentation, see the useNylasConnect reference.
Session management
Section titled “Session management”Monitor connection state changes in your React components:
function MyComponent() { const { session, getConnectionStatus } = useNylasConnect({ clientId: "<NYLAS_CLIENT_ID>", redirectUri: window.location.origin + "/auth/callback", identityProviderToken: async () => getIdpToken() });
useEffect(() => { const checkStatus = async () => { const status = await getConnectionStatus(); console.log('Connection status:', status); };
checkStatus(); }, [getConnectionStatus]);
if (session?.grantInfo) { console.log('Connected as:', session.grantInfo.email); console.log('Provider:', session.grantInfo.provider); }
return <div>{/* Your component */}</div>;}Error handling
Section titled “Error handling”Handle authentication errors in your React components:
function ConnectButton() { const [error, setError] = useState<string | null>(null); const { connect } = useNylasConnect(config);
const handleConnect = async () => { try { await connect({ method: 'popup' }); setError(null); } catch (err: any) { if (err.name === 'PopupError') { setError('Popup was blocked or closed'); } else if (err.name === 'ConfigError') { setError('Configuration error: ' + err.message); } else if (err.name === 'OAuthError') { setError('OAuth error: ' + err.message); } else { setError('Unexpected error occurred'); } } };
return ( <div> <button onClick={handleConnect}>Connect Email</button> {error && <p className="error">{error}</p>} </div> );}Best practices
Section titled “Best practices”- Provider hierarchy: Always wrap
useNylasConnectconsumers with the appropriate IDP provider component - Token refresh: IDP React hooks typically handle token refresh automatically
- Cleanup: The
useNylasConnecthook handles cleanup automatically when components unmount - Error boundaries: Use React error boundaries to catch and handle authentication errors gracefully
- Loading states: Show loading indicators while authentication is in progress
For more best practices and detailed configuration options, see the vanilla JavaScript guide.