# Nylas Connect React library overview

Source: https://developer.nylas.com/docs/v3/auth/nylas-connect-react/

Nylas maintains the [`@nylas/react` library](https://github.com/nylas/javascript/tree/main/packages/react), a React library that includes hooks and utilities to easily add a simple authentication method to your project. The main hook, [`useNylasConnect`](/docs/v3/auth/nylas-connect-react/usenylasconnect/), manages authentication state information and provides methods to connect and disconnect users.

The library also includes the prebuilt [`NylasConnectButton` UI component](/docs/v3/auth/nylas-connect-react/nylasconnectbutton/). It supports both the pop-up and redirect authentication flows, and includes default styling.

## Before you begin

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](https://github.com/nylas/javascript/tree/main/packages/react) installed in your environment.

  ```bash
  npm install @nylas/react
  ```

### Configuration settings

For projects in production, you can configure the [`useNylasConnect` hook](/docs/v3/auth/nylas-connect-react/usenylasconnect/) with the following settings.

```tsx


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

  ...
}
```

### Provider-specific configuration settings

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.

```tsx
const connectToGoogle = async () => {
  try {
    await connect({
      method: "popup",
      provider: "google",
      scopes: [
        "https://www.googleapis.com/auth/gmail.readonly",
        "https://www.googleapis.com/auth/calendar.readonly",
      ],
    });
  } catch (error) {
    console.error("Google connection failed:", error);
  }
};
```

```tsx
const connectToMicrosoft = async () => {
  try {
    await connect({
      method: "popup",
      provider: "microsoft",
      scopes: [
        "https://graph.microsoft.com/Mail.Read",
        "https://graph.microsoft.com/Calendars.Read",
      ],
    });
  } catch (error) {
    console.error("Microsoft connection failed:", error);
  }
};
```

## Set up basic authentication

The Connect React library supports two ways to set up basic authentication: using a [pop-up flow](#set-up-basic-authentication-using-pop-up-flow), or an [inline flow](#set-up-basic-authentication-using-inline-flow).

### 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).

```tsx


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

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.

```tsx


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

## Handle OAuth callback

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.

```tsx
// auth/callback route/component


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

## Set up error handling

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

```tsx


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

## Set up state management integrations

You can integrate with [Redux](https://redux.js.org/) or other libraries to add comprehensive state management capabilities to your project.

```tsx


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