Skip to content

Using external identity providers with Nylas Connect React

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 implementing external IDP integration, you need to configure two things:

  1. Nylas Dashboard Settings: Configure allowed origins and callback URIs in your Nylas Dashboard IDP settings.

  2. 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.

The React integration follows the same authentication flow as the vanilla version, but uses React hooks and context providers:

  1. Wrap your app with the IDP’s React provider (e.g., Auth0Provider, ClerkProvider)
  2. Use the IDP’s React hooks to get access tokens
  3. Pass the token to useNylasConnect via the identityProviderToken config
  4. Use the connect method from useNylasConnect to link the user’s email account

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

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

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.

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

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>
);
}
  • Provider hierarchy: Always wrap useNylasConnect consumers with the appropriate IDP provider component
  • Token refresh: IDP React hooks typically handle token refresh automatically
  • Cleanup: The useNylasConnect hook 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.