Skip to content

Using external identity providers with Nylas Connect

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.

When using an external IDP with Nylas Connect:

  1. User authenticates with your IDP: The user signs in through your identity provider (Auth0, Clerk, Google, WorkOS, etc.).
  2. IDP provides an access token: Your IDP returns an access token representing the authenticated user.
  3. Configure Nylas Connect: Pass the IDP token to Nylas Connect using the identityProviderToken option.
  4. Connect email account: User connects their email account through Nylas, which links their IDP identity to their Nylas grant.
  5. Make API calls: Use the IDP token to make authenticated Nylas API requests.

Before you can integrate an external identity provider with Nylas Connect, you need to configure the IDP settings in the Nylas Dashboard.

  1. Navigate to your application in the Nylas Dashboard.

  2. Go to Hosted AuthenticationIdentity Providers.

  3. 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 the redirectUri configured 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-settings

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 provides enterprise-grade authentication with support for various identity protocols. Here’s how to integrate Auth0 with Nylas Connect.

First, configure your Auth0 application:

  1. In your Auth0 Dashboard, navigate to ApplicationsApplications.
  2. Select your application or create a new Single Page Application.
  3. 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

Install the required packages for the Auth0 example:

npm install @auth0/auth0-spa-js
import { NylasConnect } from "@nylas/connect";
import { Auth0Client } from "@auth0/auth0-spa-js";
// Initialize Auth0
const auth0 = new Auth0Client({
domain: "<AUTH0_DOMAIN>",
clientId: "<AUTH0_CLIENT_ID>",
authorizationParams: {
redirect_uri: window.location.origin
}
});
// Initialize Nylas Connect with Auth0 token
const 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 Auth0
async 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 account
async 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);
}
}
// Logout
async function logout() {
await nylasConnect.logout();
await auth0.logout({
logoutParams: { returnTo: window.location.origin }
});
}

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 provides modern authentication with built-in UI components and session management.

First, configure your Clerk application:

  1. In your Clerk Dashboard, navigate to your application.
  2. Go to ConfigurePaths.
  3. 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., /)
  4. In Domains, add your application’s domain (e.g., localhost:3000 for development, yourapp.com for production)

Install the required packages for the Clerk example:

npm install @clerk/clerk-js
import { NylasConnect } from "@nylas/connect";
import Clerk from "@clerk/clerk-js";
// Initialize Clerk
const clerk = new Clerk("<CLERK_PUBLISHABLE_KEY>");
// Load Clerk (call this on app initialization)
async function initializeClerk() {
await clerk.load();
}
// Initialize Nylas Connect with Clerk token
const 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 Clerk
async function loginWithClerk() {
await clerk.openSignIn();
}
// Connect email account
async 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);
}
}
// Logout
async function logout() {
await nylasConnect.logout();
await clerk.signOut();
}
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 Services provides OAuth 2.0 authentication for Google accounts.

First, configure your Google Cloud project:

  1. In the Google Cloud Console, navigate to APIs & ServicesCredentials.
  2. Create or select an OAuth 2.0 Client ID.
  3. 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)
  4. 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>
import { NylasConnect } from "@nylas/connect";
// Store the Google credential
let googleCredential: string | null = null;
// Initialize Google Sign-In
function 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 token
const 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 account
async 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);
}
}
// Logout
async function logout() {
await nylasConnect.logout();
google.accounts.id.disableAutoSelect();
localStorage.removeItem("google_credential");
googleCredential = null;
}
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 provides enterprise-ready authentication with support for SSO, directory sync, and multi-factor authentication.

First, configure your WorkOS application:

  1. In your WorkOS Dashboard, navigate to ConfigurationRedirects.
  2. Add your application’s redirect URIs:
    • Development: http://localhost:3000 (or your local development URL)
    • Production: https://yourapp.com (your production domain)
  3. Note your Client ID from the Configuration page.
  4. 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-js
import { NylasConnect } from "@nylas/connect";
import { AuthKitClient } from "@workos-inc/authkit-js";
// Initialize WorkOS AuthKit
const authkit = new AuthKitClient({
clientId: "<WORKOS_CLIENT_ID>",
redirectUri: window.location.origin
});
// Initialize Nylas Connect with WorkOS token
const 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 WorkOS
async function loginWithWorkOS() {
await authkit.signIn();
}
// Check authentication status
async function checkAuth() {
const user = await authkit.getUser();
if (user) {
console.log("Authenticated as:", user.email);
return true;
}
return false;
}
// Connect email account
async 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);
}
}
// Logout
async function logout() {
await nylasConnect.logout();
await authkit.signOut();
}
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();
}

Regardless of which IDP you use, you can manage user sessions with Nylas Connect:

// Check connection status
const status = await nylasConnect.getConnectionStatus();
console.log("Status:", status); // "connected" | "expired" | "invalid" | "not_connected"
// Get session information
const 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 changes
nylasConnect.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;
}
});

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);
}
}
  • Token refresh: Ensure your identityProviderToken function 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: true in 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.