Skip to content

Nylas Connect library overview

Nylas maintains the @nylas/connect library, a JavaScript/TypeScript library that you can use to add a simple authentication mechanism to your project. It automatically manages OAuth flows, token storage, and grant creation across multiple providers, meaning you can get to making API requests more quickly.

Before you can start using the Connect library, you need…

  • A working OAuth redirect URI.

  • Your Nylas application’s client ID.

  • The @nylas/connect package installed in your environment.

The Nylas Connect library automatically detects the following environment variables:

# Client ID (required)
NYLAS_CLIENT_ID=your_client_id
# or for Vite
VITE_NYLAS_CLIENT_ID=your_client_id
# or for Next.js/public
PUBLIC_NYLAS_CLIENT_ID=your_client_id
# Redirect URI (required)
NYLAS_REDIRECT_URI=http://localhost:3000/auth/callback
# or for Vite
VITE_NYLAS_REDIRECT_URI=http://localhost:3000/auth/callback
# or for Next.js/public
PUBLIC_NYLAS_REDIRECT_URI=http://localhost:3000/auth/callback

If you want to configure your environment variables manually, you can set them in a new NylasConnect object.

const nylasConnect = new NylasConnect({
clientId: "<NYLAS_CLIENT_ID>",
redirectUri: "http://localhost:3000/auth/callback",
apiUrl: "https://api.us.nylas.com", // or https://api.eu.nylas.com
defaultScopes: [], // If not provided, we default to your connector scopes
environment: "development", // "development" | "staging" | "production"
persistTokens: true, // Store tokens in localStorage
debug: true, // Enable debug logging
logLevel: "info" // "error" | "warn" | "info" | "debug" | "off"
});

Every provider requests different information as part of its OAuth flow. You’ll need to configure the information you pass for each provider your project supports.

The Connect library supports two ways to set up basic authentication: using a pop-up flow, or an inline flow.

Set up basic authentication using pop-up flow

Section titled “Set up basic authentication using pop-up flow”

When you use the pop-up flow, your project opens the OAuth prompt in a pop-up window and the user authenticates without leaving your application. This method works well if you’re creating a single-page application (SPA).

import { NylasConnect } from "@nylas/connect";
// Initialize with environment variables (recommended)
const nylasConnect = new NylasConnect();
try {
// Start OAuth flow in popup window
const result = await nylasConnect.connect({ method: "popup" });
// Extract grant information
const { grantId, email, provider } = result;
console.log(`Connected ${email} via ${provider}`);
// Store grantId for future API calls
localStorage.setItem('nylasGrantId', grantId);
} catch (error) {
console.error('Authentication failed:', error);
}

Set up basic authentication using inline flow

Section titled “Set up basic authentication using inline flow”

When you use the inline flow, your project redirects the user’s browser to the OAuth provider where they authenticate. After the authentication process is complete, the provider returns the user to your project. We recommend this method for mobile browsers or other scenarios where the user’s browser might not support pop-ups.

// For redirect-based flow
const url = await nylasConnect.connect({ method: "inline" });
window.location.href = url;
// User will be redirected to OAuth provider

Now that you have basic authentication set up, you need to make sure your project can handle the OAuth callback.

// On your callback page (e.g., /auth/callback)
try {
const result = await nylasConnect.callback();
const { grantId, email } = result;
console.log(`Successfully authenticated: ${email}`);
} catch (error) {
console.error('Callback handling failed:', error);
}

You can set up error handling for your authentication flow using either the try-catch method or state change events that Nylas Connect generates.

Nylas Connect makes calls to the Nylas APIs to manage grants’ connection status in your project.

Your project should check users’ grant connection status intermittently to ensure they’re still authenticated.

// Check if user is connected
const isConnected = await nylasConnect.isConnected();
// Get grant information
const grantInfo = await nylasConnect.getGrantInfo();
if (grantInfo) {
console.log(`Connected as: ${grantInfo.email}`);
console.log(`Provider: ${grantInfo.provider}`);
console.log(`Grant ID: ${grantInfo.grantId}`);
}

When a user chooses to log out of your project, you need to call nylasConnect.logout(). If you don’t pass a grant ID in your call, Nylas Connect logs the current user out.

// Logout current user
await nylasConnect.logout();
// Logout specific grant
await nylasConnect.logout('specific-grant-id');

You can add support for single sign-on (SSO) to your project by including the following code.

// Check for existing session on app load
const isConnected = await nylasConnect.isConnected();
if (isConnected) {
const grantInfo = await nylasConnect.getGrantInfo();
// User is already authenticated, proceed to app
initializeApp(grantInfo);
} else {
// Show login button
showLoginButton();
}

If you want to allow your users to authenticate multiple accounts to your project, you can configure Nylas Connect to get information about all of their authenticated grants.

// Connect additional accounts
const secondAccount = await nylasConnect.connect({
method: "popup",
provider: "microsoft"
});
// Manage multiple grants
const allGrants = await Promise.all([
nylasConnect.getGrantInfo('grant-1'),
nylasConnect.getGrantInfo('grant-2')
]);