Skip to content

Nylas Connect React library overview

Nylas maintains the @nylas/react library, a React library that includes hooks and utilities to easily add a simple authentication method to your project. The main hook, useNylasConnect, manages authentication state information and provides methods to connect and disconnect users.

The library also includes the prebuilt NylasConnectButton UI component. It supports both the pop-up and redirect authentication flows, and includes default styling.

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

  • A working OAuth redirect URI.

  • Your Nylas application’s client ID.

  • The @nylas/react library installed in your environment.

    npm install @nylas/react

For projects in production, you can configure the useNylasConnect hook with the following settings.

import { useNylasConnect } from "@nylas/react/connect";
const config = {
clientId: process.env.REACT_APP_NYLAS_CLIENT_ID!,
redirectUri: process.env.REACT_APP_REDIRECT_URI!,
apiUrl: process.env.REACT_APP_NYLAS_API_URL || "https://api.us.nylas.com",
environment: process.env.NODE_ENV as "development" | "staging" | "production",
debug: process.env.NODE_ENV === "development",
};
function App() {
const { isConnected, grant, connect, logout, isLoading, error } =
useNylasConnect(config);
...
}

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 React 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 { useNylasConnect } from "@nylas/react/connect";
function App() {
const { connect, isConnected, grant, isLoading, error } = useNylasConnect({
clientId: process.env.REACT_APP_NYLAS_CLIENT_ID!,
redirectUri: process.env.REACT_APP_REDIRECT_URI!,
});
const handleConnect = async () => {
try {
const result = await connect({
method: "popup",
provider: "google",
scopes: [
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/calendar.readonly"
]
});
console.log("Connected successfully:", result);
} catch (err) {
console.error("Connection failed:", err);
}
};
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
if (isConnected && grant) {
return <div>Welcome, {grant.email}!</div>;
}
return <button onClick={handleConnect}>Connect with Google</button>;
}

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.

import { useNylasConnect } from "@nylas/react/connect";
function App() {
const { connect, isConnected, grant, isLoading, error } = useNylasConnect({
clientId: process.env.REACT_APP_NYLAS_CLIENT_ID!,
redirectUri: process.env.REACT_APP_REDIRECT_URI!,
});
const handleConnect = async () => {
try {
// With inline method, connect returns a URL string
const authUrl = await connect({
method: "inline",
provider: "microsoft",
});
// Redirect to the authentication URL
window.location.href = authUrl as string;
} catch (err) {
console.error("Connection failed:", err);
}
};
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
if (isConnected && grant) {
return <div>Welcome, {grant.email}!</div>;
}
return <button onClick={handleConnect}>Connect with Microsoft</button>;
}

Now that you have basic authentication set up, you need to make sure your project can handle the OAuth callback. The following example handles OAuth callbacks in a dedicated route.

// auth/callback route/component
import { useNylasConnect } from "@nylas/react/connect";
import { useEffect, useState } from "react";
export default function AuthCallback() {
const { connectClient } = useNylasConnect(config);
const [status, setStatus] = useState<"processing" | "success" | "error">("processing");
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const handleCallback = async () => {
try {
if (!connectClient) return;
// Handle the OAuth callback
const result = await connectClient.callback();
setStatus("success");
// Redirect to dashboard after successful auth
setTimeout(() => {
window.location.href = "/dashboard";
}, 2000);
} catch (err: any) {
console.error("Callback handling failed:", err);
setError(err.message);
setStatus("error");
}
};
handleCallback();
}, [connectClient]);
if (status === "processing") {
return <div>Processing authentication...</div>;
}
if (status === "success") {
return (
<div>
<h2>Authentication Successful!</h2>
<p>Redirecting to your dashboard...</p>
</div>
);
}
return (
<div>
<h2>Authentication Failed</h2>
<p>{error}</p>
<button onClick={() => { window.location.href = "/"; }}>
Back to Home
</button>
</div>
);
}

The following example implements comprehensive error handling methods for different scenarios.

import { useNylasConnect } from "@nylas/react/connect";
import { useState } from "react";
function AuthComponent() {
const { isConnected, connect, error } = useNylasConnect(config);
const [connectionError, setConnectionError] = useState<string | null>(null);
const handleConnect = async (method: "popup" | "inline") => {
setConnectionError(null);
try {
await connect({ method });
} catch (err: any) {
// Handle specific error types
if (err.message?.includes("popup_blocked")) {
setConnectionError("Popup was blocked. Please allow popups and try again.");
} else if (err.message?.includes("user_cancelled")) {
setConnectionError("Authentication was cancelled.");
} else if (err.message?.includes("network")) {
setConnectionError("Network error. Please check your connection and try again.");
} else {
setConnectionError(`Authentication failed: ${err.message}`);
}
}
};
const displayError = error || connectionError;
if (displayError) {
return (
<div>
<h3>Authentication Error</h3>
<p>{displayError}</p>
<button onClick={() => setConnectionError(null)}>
Dismiss
</button>
</div>
);
}
return (
<div>
<button onClick={() => handleConnect("popup")}>
Connect with Popup
</button>
<button onClick={() => handleConnect("inline")}>
Connect with Redirect
</button>
</div>
);
}

You can integrate with Redux or other libraries to add comprehensive state management capabilities to your project.

import { useNylasConnect } from "@nylas/react/connect";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { setUser, clearUser, setAuthError } from "./store/authSlice";
function AuthProvider({ children }: { children: React.ReactNode }) {
const dispatch = useDispatch();
const { isConnected, grant, error, connectClient } = useNylasConnect(config);
useEffect(() => {
if (isConnected && grant) {
dispatch(setUser({
id: grant.id,
email: grant.email,
name: grant.name,
provider: grant.provider,
picture: grant.picture
}));
} else if (!isConnected) {
dispatch(clearUser());
}
}, [isConnected, grant, dispatch]);
useEffect(() => {
if (error) {
dispatch(setAuthError(error.message));
}
}, [error, dispatch]);
// Make connectClient available to child components
useEffect(() => {
if (connectClient) {
// Store client instance for API calls
window.nylasConnect = connectClient;
}
}, [connectClient]);
return <>{children}</>;
}