You can integrate external identity providers (IDPs) with Nylas Connect to authenticate users through your existing identity system. This allows you to link your users’ IDP identities with their Nylas grants, enabling seamless API calls without managing separate authentication flows.
How it works
Section titled “How it works”When using an external IDP with Nylas Connect:
- User authenticates with your IDP: The user signs in through your identity provider (Auth0, Clerk, Google, WorkOS, etc.).
- IDP provides an access token: Your IDP returns an access token representing the authenticated user.
- Configure Nylas Connect: Pass the IDP token to Nylas Connect using the
identityProviderTokenoption. - Connect email account: User connects their email account through Nylas, which links their IDP identity to their Nylas grant.
- Make API calls: Use the IDP token to make authenticated Nylas API requests.
Before you begin
Section titled “Before you begin”Before you can integrate an external identity provider with Nylas Connect, you need to configure the IDP settings in the Nylas Dashboard.
Configure identity provider settings
Section titled “Configure identity provider settings”-
Navigate to your application in the Nylas Dashboard.
-
Go to Hosted Authentication → Identity Providers.
-
Configure the following settings:
-
Allowed Origins: Add the domains where your application will be hosted (e.g.,
http://localhost:3000,https://yourapp.com). These origins will be allowed to make requests to Nylas with your IDP tokens. -
Callback URIs: Add the redirect URIs that Nylas will use after authentication (e.g.,
http://localhost:3000/auth/callback). These must match theredirectUriconfigured in your NylasConnect instance.
-
You can access the Identity Provider settings page directly at:
https://dashboard-v3.nylas.com/applications/<YOUR_APP_ID>/hosted-authentication/idp-settingsConfiguration
Section titled “Configuration”To use an external IDP, configure your NylasConnect instance with an identityProviderToken function that returns the current user’s IDP access token:
import { NylasConnect } from "@nylas/connect";
const nylasConnect = new NylasConnect({ clientId: "<NYLAS_CLIENT_ID>", redirectUri: "http://localhost:3000/auth/callback", identityProviderToken: async () => { // Return the IDP access token for the current user return await getIdpToken(); }});Auth0 integration
Section titled “Auth0 integration”Auth0 provides enterprise-grade authentication with support for various identity protocols. Here’s how to integrate Auth0 with Nylas Connect.
First, configure your Auth0 application:
- In your Auth0 Dashboard, navigate to Applications → Applications.
- Select your application or create a new Single Page Application.
- Configure the following settings:
- Allowed Callback URLs: Add your application’s callback URLs (e.g.,
http://localhost:3000,https://yourapp.com) - Allowed Web Origins: Add your application’s origins (e.g.,
http://localhost:3000,https://yourapp.com) - Allowed Logout URLs: Add URLs where users can be redirected after logout
- Allowed Callback URLs: Add your application’s callback URLs (e.g.,
Install the required packages for the Auth0 example:
npm install @auth0/auth0-spa-jsImplementation
Section titled “Implementation”import { NylasConnect } from "@nylas/connect";import { Auth0Client } from "@auth0/auth0-spa-js";
// Initialize Auth0const auth0 = new Auth0Client({ domain: "<AUTH0_DOMAIN>", clientId: "<AUTH0_CLIENT_ID>", authorizationParams: { redirect_uri: window.location.origin }});
// Initialize Nylas Connect with Auth0 tokenconst nylasConnect = new NylasConnect({ clientId: "<NYLAS_CLIENT_ID>", redirectUri: "http://localhost:3000/auth/callback", identityProviderToken: async () => { try { return await auth0.getTokenSilently(); } catch (error) { console.error("Failed to get Auth0 token:", error); return null; } }});
// Authenticate with Auth0async function loginWithAuth0() { await auth0.loginWithPopup(); const isAuthenticated = await auth0.isAuthenticated();
if (isAuthenticated) { const user = await auth0.getUser(); console.log("Authenticated as:", user?.email); }}
// Connect email accountasync function connectEmail() { try { const result = await nylasConnect.connect({ method: "popup" }); console.log("Email connected:", result.grantInfo?.email); } catch (error) { console.error("Failed to connect email:", error); }}
// Logoutasync function logout() { await nylasConnect.logout(); await auth0.logout({ logoutParams: { returnTo: window.location.origin } });}Making API calls
Section titled “Making API calls”Extract the user ID from the Auth0 token to make API calls:
function parseSubFromJwt(token: string): string | null { try { const base64Payload = token.split(".")[1]; const payload = JSON.parse(atob(base64Payload)); return payload?.sub || null; } catch { return null; }}
async function fetchEmails() { const token = await auth0.getTokenSilently(); const userId = parseSubFromJwt(token);
const response = await fetch( `https://api.us.nylas.com/v3/grants/me/messages`, { headers: { Authorization: `Bearer ${token}`, "X-Nylas-External-User-Id": userId || "" } } );
return await response.json();}Clerk integration
Section titled “Clerk integration”Clerk provides modern authentication with built-in UI components and session management.
First, configure your Clerk application:
- In your Clerk Dashboard, navigate to your application.
- Go to Configure → Paths.
- Configure the following settings:
- Sign-in URL: Set to your application’s sign-in page (e.g.,
/sign-in) - Sign-up URL: Set to your application’s sign-up page (e.g.,
/sign-up) - After sign-in URL: Set to where users should land after signing in (e.g.,
/) - After sign-up URL: Set to where users should land after signing up (e.g.,
/)
- Sign-in URL: Set to your application’s sign-in page (e.g.,
- In Domains, add your application’s domain (e.g.,
localhost:3000for development,yourapp.comfor production)
Install the required packages for the Clerk example:
npm install @clerk/clerk-jsImplementation
Section titled “Implementation”import { NylasConnect } from "@nylas/connect";import Clerk from "@clerk/clerk-js";
// Initialize Clerkconst clerk = new Clerk("<CLERK_PUBLISHABLE_KEY>");
// Load Clerk (call this on app initialization)async function initializeClerk() { await clerk.load();}
// Initialize Nylas Connect with Clerk tokenconst nylasConnect = new NylasConnect({ clientId: "<NYLAS_CLIENT_ID>", redirectUri: "http://localhost:3000/auth/callback", identityProviderToken: async () => { try { const token = await clerk.session?.getToken(); return token || null; } catch (error) { console.error("Failed to get Clerk token:", error); return null; } }});
// Authenticate with Clerkasync function loginWithClerk() { await clerk.openSignIn();}
// Connect email accountasync function connectEmail() { try { const result = await nylasConnect.connect({ method: "popup" }); console.log("Email connected:", result.grantInfo?.email); } catch (error) { console.error("Failed to connect email:", error); }}
// Logoutasync function logout() { await nylasConnect.logout(); await clerk.signOut();}Making API calls
Section titled “Making API calls”function parseSubFromJwt(token: string): string | null { try { const base64Payload = token.split(".")[1]; const payload = JSON.parse(atob(base64Payload)); return payload?.sub || null; } catch { return null; }}
async function fetchEmails() { const token = await clerk.session?.getToken(); const userId = parseSubFromJwt(token || "");
const response = await fetch( `https://api.us.nylas.com/v3/grants/me/messages`, { headers: { Authorization: `Bearer ${token}`, "X-Nylas-External-User-Id": userId || "" } } );
return await response.json();}Google Identity integration
Section titled “Google Identity integration”Google Identity Services provides OAuth 2.0 authentication for Google accounts.
First, configure your Google Cloud project:
- In the Google Cloud Console, navigate to APIs & Services → Credentials.
- Create or select an OAuth 2.0 Client ID.
- Configure the following settings:
- Application type: Select “Web application”
- Authorized JavaScript origins: Add your application’s origins (e.g.,
http://localhost:3000,https://yourapp.com) - Authorized redirect URIs: Add your application’s callback URLs (e.g.,
http://localhost:3000,https://yourapp.com)
- Save your Client ID for use in your application.
Load the Google Identity Services library in your HTML for the Google example:
<script src="https://accounts.google.com/gsi/client" async defer></script>Implementation
Section titled “Implementation”import { NylasConnect } from "@nylas/connect";
// Store the Google credentiallet googleCredential: string | null = null;
// Initialize Google Sign-Infunction initializeGoogleSignIn() { google.accounts.id.initialize({ client_id: "<GOOGLE_CLIENT_ID>", callback: handleGoogleResponse });
google.accounts.id.renderButton( document.getElementById("googleSignInButton"), { theme: "outline", size: "large" } );}
function handleGoogleResponse(response: any) { googleCredential = response.credential; localStorage.setItem("google_credential", googleCredential); console.log("Google authentication successful");}
// Initialize Nylas Connect with Google tokenconst nylasConnect = new NylasConnect({ clientId: "<NYLAS_CLIENT_ID>", redirectUri: "http://localhost:3000/auth/callback", provider: "google", identityProviderToken: async () => { try { return localStorage.getItem("google_credential"); } catch { return null; } }});
// Connect email accountasync function connectEmail() { try { const result = await nylasConnect.connect({ method: "popup" }); console.log("Email connected:", result.grantInfo?.email); } catch (error) { console.error("Failed to connect email:", error); }}
// Logoutasync function logout() { await nylasConnect.logout(); google.accounts.id.disableAutoSelect(); localStorage.removeItem("google_credential"); googleCredential = null;}Making API calls
Section titled “Making API calls”function parseJwt(token: string): any { try { const base64Payload = token.split(".")[1]; return JSON.parse(atob(base64Payload)); } catch { return {}; }}
async function fetchEmails() { const token = localStorage.getItem("google_credential"); const payload = parseJwt(token || ""); 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 || "" } } );
return await response.json();}WorkOS integration
Section titled “WorkOS integration”WorkOS provides enterprise-ready authentication with support for SSO, directory sync, and multi-factor authentication.
First, configure your WorkOS application:
- In your WorkOS Dashboard, navigate to Configuration → Redirects.
- Add your application’s redirect URIs:
- Development:
http://localhost:3000(or your local development URL) - Production:
https://yourapp.com(your production domain)
- Development:
- Note your Client ID from the Configuration page.
- Configure any additional SSO connections or authentication methods you need under Authentication.
Install the required packages for the WorkOS example:
npm install @workos-inc/authkit-jsImplementation
Section titled “Implementation”import { NylasConnect } from "@nylas/connect";import { AuthKitClient } from "@workos-inc/authkit-js";
// Initialize WorkOS AuthKitconst authkit = new AuthKitClient({ clientId: "<WORKOS_CLIENT_ID>", redirectUri: window.location.origin});
// Initialize Nylas Connect with WorkOS tokenconst nylasConnect = new NylasConnect({ clientId: "<NYLAS_CLIENT_ID>", redirectUri: "http://localhost:3000/auth/callback", identityProviderToken: async () => { try { const token = await authkit.getToken(); return token || null; } catch (error) { console.error("Failed to get WorkOS token:", error); return null; } }});
// Authenticate with WorkOSasync function loginWithWorkOS() { await authkit.signIn();}
// Check authentication statusasync function checkAuth() { const user = await authkit.getUser(); if (user) { console.log("Authenticated as:", user.email); return true; } return false;}
// Connect email accountasync function connectEmail() { try { const result = await nylasConnect.connect({ method: "popup" }); console.log("Email connected:", result.grantInfo?.email); } catch (error) { console.error("Failed to connect email:", error); }}
// Logoutasync function logout() { await nylasConnect.logout(); await authkit.signOut();}Making API calls
Section titled “Making API calls”function parseSubFromJwt(token: string): string | null { try { const base64Payload = token.split(".")[1]; const payload = JSON.parse(atob(base64Payload)); return payload?.sub || null; } catch { return null; }}
async function fetchEmails() { const token = await authkit.getToken(); const userId = parseSubFromJwt(token || "");
const response = await fetch( `https://api.us.nylas.com/v3/grants/me/messages`, { headers: { Authorization: `Bearer ${token}`, "X-Nylas-External-User-Id": userId || "" } } );
return await response.json();}Session management
Section titled “Session management”Regardless of which IDP you use, you can manage user sessions with Nylas Connect:
// Check connection statusconst status = await nylasConnect.getConnectionStatus();console.log("Status:", status); // "connected" | "expired" | "invalid" | "not_connected"
// Get session informationconst session = await nylasConnect.getSession();if (session?.grantInfo) { console.log("Connected as:", session.grantInfo.email); console.log("Provider:", session.grantInfo.provider); console.log("Grant ID:", session.grantId);}
// Listen for connection state changesnylasConnect.onConnectStateChange((event, session, data) => { switch (event) { case "CONNECT_SUCCESS": console.log("Successfully connected:", session?.grantInfo?.email); break; case "CONNECT_ERROR": console.error("Connection failed:", data?.error); break; case "CONNECT_CANCELLED": console.log("User cancelled authentication"); break; }});Error handling
Section titled “Error handling”Handle errors when integrating with external IDPs:
try { const result = await nylasConnect.connect({ method: "popup" }); console.log("Connection successful:", result);} catch (error) { if (error.name === "PopupError") { console.error("Popup was blocked or closed"); } else if (error.name === "ConfigError") { console.error("Configuration error:", error.message); } else if (error.name === "OAuthError") { console.error("OAuth error:", error.message); } else { console.error("Unexpected error:", error); }}Best practices
Section titled “Best practices”- Token refresh: Ensure your
identityProviderTokenfunction returns fresh tokens. Most IDP SDKs handle token refresh automatically. - Error handling: Always handle cases where the IDP token is unavailable or expired.
- Secure storage: Store tokens securely and never expose them in client-side code that could be compromised.
- Session persistence: Use
persistTokens: truein your Nylas Connect configuration to maintain sessions across page reloads. - User experience: Provide clear feedback when authentication fails or when users need to re-authenticate with either the IDP or email provider.