# Using external identity providers with Nylas Connect React

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

You can integrate external identity providers (IDPs) with the Nylas Connect React library to authenticate users through your existing identity system. This guide covers the React-specific integration pattern using the `useNylasConnect` hook.

> **Tip:** 
> If you're not using React, see the [vanilla JavaScript guides](/docs/v3/auth/nylas-connect/use-external-idp/) for implementation details using `@nylas/connect` directly.

## Supported identity providers

| Provider   | Guide                                                                        |
| ---------- | ---------------------------------------------------------------------------- |
| **Auth0**  | [Auth0 + React](/docs/v3/auth/nylas-connect-react/use-external-idp/auth0/)   |
| **Clerk**  | [Clerk + React](/docs/v3/auth/nylas-connect-react/use-external-idp/clerk/)   |
| **Google** | [Google + React](/docs/v3/auth/nylas-connect-react/use-external-idp/google/) |
| **WorkOS** | [WorkOS + React](/docs/v3/auth/nylas-connect-react/use-external-idp/workos/) |

For custom identity providers, see the [custom IDP guide](/docs/v3/auth/nylas-connect/use-external-idp/custom/) (vanilla JavaScript) and adapt the pattern using `useNylasConnect`.

## Before you begin

Before implementing external IDP integration, you need to configure two things:

1. **Nylas Dashboard Settings**: Configure allowed origins and callback URIs in your [Nylas Dashboard IDP settings](https://dashboard-v3.nylas.com/applications/<YOUR_APP_ID>/hosted-authentication/idp-settings).

2. **Provider Configuration**: Set up callback URLs and origins in your identity provider's dashboard.

See the [vanilla JavaScript overview](/docs/v3/auth/nylas-connect/use-external-idp/#before-you-begin) for detailed Nylas Dashboard setup steps.

## How it works

The React integration follows the same authentication flow as the vanilla version, but uses the `useNylasConnect` hook alongside your IDP's React SDK:

1. Wrap your app with the IDP's React provider (e.g., `Auth0Provider`, `ClerkProvider`)
2. Use the IDP's React hooks to get access tokens
3. Pass the token to `useNylasConnect` via the `identityProviderToken` config
4. Use the `connect` method from `useNylasConnect` to link the user's email account

## useNylasConnect hook reference

The `useNylasConnect` hook returns state, actions, and a reference to the underlying `NylasConnect` client:

```tsx
const {
  // State
  isConnected, // boolean: whether an email account is connected
  grant, // GrantInfo | null: connected account info (email, provider, id, etc.)
  isLoading, // boolean: whether an auth operation is in progress
  error, // Error | null: last error from an auth operation

  // Actions
  connect, // (options?) => Promise<ConnectResult | string>: start email connection
  logout, // (grantId?) => Promise<void>: disconnect email account
  refreshSession, // () => Promise<void>: re-fetch session state
  subscribe, // (callback) => () => void: listen for connection events
  setLogLevel, // (level) => void: set log level

  // Direct access
  connectClient, // NylasConnect: the underlying client instance
} = useNylasConnect(config);
```

Use `connectClient` to access lower-level methods like `getConnectionStatus()` or `getSession()` that aren't exposed directly by the hook.

For complete hook documentation, see the [useNylasConnect reference](/docs/v3/auth/nylas-connect-react/usenylasconnect/).

## Session management

Monitor connection state in your React components using the `grant` state and `connectClient` for lower-level checks:

```tsx
function MyComponent() {
  const { grant, isConnected, connectClient } = useNylasConnect({
    clientId: "<NYLAS_CLIENT_ID>",
    redirectUri: window.location.origin + "/auth/callback",
    identityProviderToken: async () => getIdpToken(),
  });

  useEffect(() => {
    const checkStatus = async () => {
      const status = await connectClient.getConnectionStatus();
      console.log("Connection status:", status);
    };

    checkStatus();
  }, [connectClient]);

  if (grant) {
    console.log("Connected as:", grant.email);
    console.log("Provider:", grant.provider);
  }

  return <div>{/* Your component */}</div>;
}
```

## Error handling

Handle authentication errors in your React components:

```tsx
function ConnectButton() {
  const [error, setError] = useState<string | null>(null);
  const { connect } = useNylasConnect(config);

  const handleConnect = async () => {
    try {
      await connect({ method: "popup" });
      setError(null);
    } catch (err: any) {
      if (err.name === "PopupError") {
        setError("Popup was blocked or closed");
      } else if (err.name === "ConfigError") {
        setError("Configuration error: " + err.message);
      } else if (err.name === "OAuthError") {
        setError("OAuth error: " + err.message);
      } else {
        setError("Unexpected error occurred");
      }
    }
  };

  return (
    <div>
      <button onClick={handleConnect}>Connect Email</button>
      {error && <p className="error">{error}</p>}
    </div>
  );
}
```

## Best practices

- **Provider hierarchy**: Always wrap `useNylasConnect` consumers with the appropriate IDP provider component
- **Token refresh**: IDP React hooks typically handle token refresh automatically
- **Cleanup**: The `useNylasConnect` hook handles cleanup automatically when components unmount
- **Error boundaries**: Use React error boundaries to catch and handle authentication errors gracefully
- **Loading states**: Show loading indicators while authentication is in progress