# NylasConnectButton component

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

The `NylasConnectButton` is a prebuilt React component that triggers the Nylas Connect authentication flow. It supports both pop-up and redirect methods, includes sensible loading/disabled states, and offers styling options out of the box.

```tsx


export default function ConnectCTA() {
  return (
    
  );
}
```

The component renders as `<button type="button">`. When a connection is in progress, the button is disabled and sets `aria-busy` for accessibility purposes.

We recommend using the `NylasConnectButton` component when you want a drag-and-drop authentication experience with minimal setup. If you need custom UI or UX, or more granular control over state, use the [`useNylasConnect` hook](/docs/v3/auth/nylas-connect-react/usenylasconnect/) instead.

## Important: Conditional rendering and callbacks

The `NylasConnectButton` automatically handles OAuth callbacks when the component is mounted. However, if you render the button conditionally (for example, only when the user is not authenticated), the button won't be present on the callback page to handle the OAuth response.

**If you conditionally render the button, you must handle the callback yourself using the [`useNylasConnect` hook](/docs/v3/auth/nylas-connect-react/usenylasconnect/).**

### ✅ Correct: Unconditional rendering

The button is always rendered, so it can handle the callback automatically:

```tsx


function App() {
  return (
    <NylasConnectButton
      clientId={process.env.NYLAS_CLIENT_ID!}
      redirectUri={process.env.NYLAS_REDIRECT_URI!}
      onSuccess={(result) => {
        console.log("Connected:", result.grantInfo?.email);
      }}
    />
  );
}
```

### ❌ Incorrect: Conditional rendering without manual callback handling

The button won't be mounted on the callback page, so the OAuth response won't be processed:

```tsx


function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  // ❌ Button won't be present after redirect, callback won't be handled
  return (
    <div>
      {!isAuthenticated && (
        
      )}
    </div>
  );
}
```

### ✅ Correct: Conditional rendering with manual callback handling

Use the hook to handle callbacks manually when rendering conditionally:

```tsx


function App() {
  const { isConnected, grant, connect, isLoading } = useNylasConnect({
    clientId: process.env.NYLAS_CLIENT_ID!,
    redirectUri: process.env.NYLAS_REDIRECT_URI!,
    autoHandleCallback: true, // Hook handles callback automatically
  });

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (isConnected && grant) {
    return (
      <div>
        <h2>Welcome, {grant.email}!</h2>
        <p>Provider: {grant.provider}</p>
      </div>
    );
  }

  // Now it's safe to conditionally render the button
  return (
    <button
      onClick={async () => {
        try {
          await connect({ method: "inline" });
        } catch (error) {
          console.error("Connection failed:", error);
        }
      }}
    >
      Connect your account
    </button>
  );
}
```

## Properties

### `apiUrl?`

|                 |                                                          |
| --------------- | -------------------------------------------------------- |
| **Name**        | `apiUrl`                                                 |
| **Description** | The Nylas API base URL.                                  |
| **Type**        | `https://api.us.nylas.com` \| `https://api.eu.nylas.com` |
| **Default**     | `https://api.us.nylas.com`                               |

### `children?`

|                 |                                                   |
| --------------- | ------------------------------------------------- |
| **Name**        | `children`                                        |
| **Description** | Custom button content. Overrides [`text`](#text). |
| **Type**        | `ReactNode?`                                      |

### `className?`

|                 |                                                                    |
| --------------- | ------------------------------------------------------------------ |
| **Name**        | `className`                                                        |
| **Description** | Additional class names to add to the `NylasConnectButton` element. |
| **Type**        | string?                                                            |

### `clientId`

|                 |                                     |
| --------------- | ----------------------------------- |
| **Name**        | `clientId`                          |
| **Description** | Your Nylas application's client ID. |
| **Type**        | string                              |

### `codeExchange?`

|                 |                                                                            |
| --------------- | -------------------------------------------------------------------------- |
| **Name**        | `codeExchange`                                                             |
| **Description** | A custom backend code exchange. This replaces the built-in token exchange. |
| **Type**        | `CodeExchangeMethod?`                                                      |

### `cssVars?`

|                 |                                                                                              |
| --------------- | -------------------------------------------------------------------------------------------- |
| **Name**        | `cssVars`                                                                                    |
| **Description** | A set of custom CSS properties (for example, `--nylas-btn-bg`, `--nylas-btn-fg`, and so on). |
| **Type**        | `Record<string, string>?`                                                                    |

### `defaultScopes?`

|                 |                                                                                                                                                                                                    |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Name**        | `defaultScopes`                                                                                                                                                                                    |
| **Description** | Default scopes to configure for the `NylasConnect` instance. These scopes are used when [`scopes`](#scopes) is not provided. This is a **configuration option** that sets defaults for the client. |
| **Type**        | `NylasScope[]?`                                                                                                                                                                                    |

### `disabled?`

|                 |                                                 |
| --------------- | ----------------------------------------------- |
| **Name**        | `disabled`                                      |
| **Description** | When `true`, disables the `NylasConnectButton`. |
| **Type**        | boolean?                                        |

### `identityProviderToken?`

|                 |                                                                                                               |
| --------------- | ------------------------------------------------------------------------------------------------------------- |
| **Name**        | `identityProviderToken`                                                                                       |
| **Description** | A callback that returns an external identity provider JWT. This is set to `idp_claims` during token exchange. |
| **Type**        | `() => Promise<string \| null> \| string \| null`                                                             |

### `loginHint?`

|                 |                                                                   |
| --------------- | ----------------------------------------------------------------- |
| **Name**        | `loginHint`                                                       |
| **Description** | An email address to pre-fill on the provider authentication page. |
| **Type**        | string?                                                           |

### `method?`

|                 |                                                                                                                                                                                                                 |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Name**        | `method`                                                                                                                                                                                                        |
| **Description** | Specify the authentication method. When `inline`, redirects the user to the provider using the URL returned from `connect()`. When `popup`, opens a pop-up window and resolves with `ConnectResult` on success. |
| **Type**        | `popup` \| `inline`                                                                                                                                                                                             |
| **Default**     | `inline`                                                                                                                                                                                                        |

### `persistTokens?`

|                 |                                                                                                             |
| --------------- | ----------------------------------------------------------------------------------------------------------- |
| **Name**        | `persistTokens`                                                                                             |
| **Description** | When `true`, Nylas Connect stores tokens in `localStorage`. When `false`, tokens are stored in memory only. |
| **Type**        | `boolean?`                                                                                                  |
| **Default**     | `true`                                                                                                      |

### `popupHeight?`

|                 |                                                                                               |
| --------------- | --------------------------------------------------------------------------------------------- |
| **Name**        | `popupHeight`                                                                                 |
| **Description** | The height of the authentication pop-up, in pixels. Used when [`method`](#method) is `popup`. |
| **Type**        | number?                                                                                       |
| **Default**     | 600                                                                                           |

### `popupWidth?`

|                 |                                                                                              |
| --------------- | -------------------------------------------------------------------------------------------- |
| **Name**        | `popupWidth`                                                                                 |
| **Description** | The width of the authentication pop-up, in pixels. Used when [`method`](#method) is `popup`. |
| **Type**        | number?                                                                                      |
| **Default**     | 500                                                                                          |

### `provider?`

|                 |                                                                       |
| --------------- | --------------------------------------------------------------------- |
| **Name**        | `provider`                                                            |
| **Description** | The OAuth provider that Nylas Connect will use to authenticate users. |
| **Type**        | `Provider?`                                                           |

### `redirectUri?`

|                 |                                                                     |
| --------------- | ------------------------------------------------------------------- |
| **Name**        | `redirectUri`                                                       |
| **Description** | The OAuth redirect URI that matches your application configuration. |
| **Type**        | string?                                                             |

### `scopes?`

|                 |                                                                                                                                                                                                                                     |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Name**        | `scopes`                                                                                                                                                                                                                            |
| **Description** | Scopes to request for this specific authentication attempt. This is an **option property** that overrides [`defaultScopes`](#defaultscopes) when provided. Use this to request different scopes for individual connection attempts. |
| **Type**        | `NylasScope[]?`                                                                                                                                                                                                                     |

### `size?`

|                 |                                                                            |
| --------------- | -------------------------------------------------------------------------- |
| **Name**        | `size`                                                                     |
| **Description** | The size of the `NylasConnectButton` when using one of the default styles. |
| **Type**        | `sm` \| `md` \| `lg`                                                       |
| **Default**     | `md`                                                                       |

### `style?`

|                 |                                             |
| --------------- | ------------------------------------------- |
| **Name**        | `style`                                     |
| **Description** | Inline styles for the `NylasConnectButton`. |
| **Type**        | `CSSProperties?`                            |

### `text?`

|                 |                                                                                                            |
| --------------- | ---------------------------------------------------------------------------------------------------------- |
| **Name**        | `text`                                                                                                     |
| **Description** | Text to be displayed as the `NylasConnectButton` label. Ignored when [`children`](#children) is specified. |
| **Type**        | string?                                                                                                    |
| **Default**     | "Connect your inbox"                                                                                       |

### `unstyled?`

|                 |                                                                       |
| --------------- | --------------------------------------------------------------------- |
| **Name**        | `unstyled`                                                            |
| **Description** | When `true`, disables the default `NylasConnectButton` style classes. |
| **Type**        | boolean?                                                              |
| **Default**     | `false`                                                               |

### `variant?`

|                 |                                                                 |
| --------------- | --------------------------------------------------------------- |
| **Name**        | `variant`                                                       |
| **Description** | The visual variant for the default `NylasConnectButton` styles. |
| **Type**        | `primary` \| `outline`                                          |
| **Default**     | `primary`                                                       |

## Events

| Event       | Type                               | Description                                                                                        |
| ----------- | ---------------------------------- | -------------------------------------------------------------------------------------------------- |
| `onCancel`  | `(reason: string) => void?`        | Called when the user cancels the authentication flow or closes the pop-up.                         |
| `onError`   | `(error: Error) => void?`          | Called when an error occurs during authentication.                                                 |
| `onStart`   | `() => void?`                      | Called when the user clicks the button and the authentication flow begins.                         |
| `onSuccess` | `(result: ConnectResult) => void?` | Called when the pop-up authentication flow completes and the provider returns tokens for the user. |

## Code samples

```tsx [samples-Pop-up method]

```

```tsx [samples-Inline method]

```

```tsx [samples-Callback events]
<NylasConnectButton
  clientId="..."
  redirectUri="..."
  onStart={() => console.log("starting")}
  onSuccess={(res) => console.log("success", res)}
  onCancel={(reason) => console.log("cancel", reason)}
  onError={(e) => console.error("error", e)}
/>
```

```tsx [samples-Custom styling]

```

```tsx [samples-Backend code exchange]
// Advanced: backend code exchange and external identity provider token
<NylasConnectButton
  clientId="..."
  redirectUri="..."
  codeExchange={async (params) => {
    const res = await fetch("/api/auth/exchange", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(params),
    });
    if (!res.ok) throw new Error("Token exchange failed");
    return await res.json();
  }}
  identityProviderToken={async () => {
    // Return a JWT string from your identity provider, or null
    return null;
  }}
/>
```