# Integrate WorkOS with Nylas Connect

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

WorkOS provides enterprise-ready authentication with support for SSO, directory sync, and multi-factor authentication through its AuthKit library. This guide shows you how to use WorkOS as your identity provider with Nylas Connect so your users can authenticate through WorkOS and connect their email accounts through Nylas.

WorkOS is a strong choice if your application serves enterprise customers who require SAML/OIDC SSO, SCIM directory sync, or audit logs.

## Before you begin

You need a WorkOS application and a Nylas application configured to work together.


### Configure Nylas Dashboard

Before connecting your identity provider, configure the IDP settings in the Nylas Dashboard:

1. Navigate to your application in the [Nylas Dashboard](https://dashboard-v3.nylas.com).
2. Go to **Hosted Authentication** → **Identity Providers**.
3. Configure the following settings:
   - **Allowed Origins**: Add the domains where your application will be hosted (e.g., `http://localhost:3000`, `https://yourapp.com`). These origins will be allowed to make requests to Nylas with your IDP tokens.
   - **Callback URIs**: Add the redirect URIs that Nylas will use after authentication (e.g., `http://localhost:3000/auth/callback`). These must match the `redirectUri` configured in your NylasConnect instance.

> **Note:** 
> The allowed origins and callback URIs are security measures to prevent unauthorized use of your Nylas application. Include all domains where your application will run, including development, staging, and production environments.

You can access the Identity Provider settings page directly at:

```
https://dashboard-v3.nylas.com/applications/<YOUR_APP_ID>/hosted-authentication/idp-settings
```


### Configure WorkOS

1. In your [WorkOS Dashboard](https://dashboard.workos.com/), navigate to **Configuration** → **Redirects**.
2. Add your application's redirect URIs:
   - **Development**: `http://localhost:3000` (or your local development URL)
   - **Production**: `https://yourapp.com` (your production domain)
3. Note your **Client ID** from the Configuration page.
4. Configure any additional SSO connections or authentication methods you need under **Authentication**.

> **Local development setup:** 
> This guide uses `http://localhost:3000` in all examples. If you're developing on a different port:
> 
> - Add your actual development URL (e.g., `http://localhost:5173`) to the WorkOS Dashboard's redirect URIs
> - Update the `redirectUri` in your WorkOS AuthKit client initialization (set to `window.location.origin` in the example below)
> - Update the `redirectUri` in your Nylas Connect configuration
> - Update the **Allowed Origins** and **Callback URIs** in your Nylas Dashboard's Identity Provider settings
> 
> Ensure all these URLs are consistent across your WorkOS, Nylas, and application configurations.

### Install dependencies

```bash
npm install @nylas/connect @workos-inc/authkit-js
```

## Implementation

Initialize WorkOS AuthKit and Nylas Connect together. The `identityProviderToken` callback retrieves the token from AuthKit and passes it to Nylas Connect:

```ts


const authkit = new AuthKitClient({
  clientId: "<WORKOS_CLIENT_ID>",
  redirectUri: window.location.origin,
});

const nylasConnect = new NylasConnect({
  clientId: "<NYLAS_CLIENT_ID>",
  redirectUri: "http://localhost:3000/auth/callback",
  identityProviderToken: async () => {
    try {
      const token = await authkit.getToken();
      return token || null;
    } catch (error) {
      console.error("Failed to get WorkOS token:", error);
      return null;
    }
  },
});

async function loginWithWorkOS() {
  await authkit.signIn();
}

async function checkAuth() {
  const user = await authkit.getUser();
  if (user) {
    console.log("Authenticated as:", user.email);
    return true;
  }
  return false;
}

async function connectEmail() {
  try {
    const result = await nylasConnect.connect({ method: "popup" });
    console.log("Email connected:", result.grantInfo?.email);
  } catch (error) {
    console.error("Failed to connect email:", error);
  }
}

async function logout() {
  await nylasConnect.logout();
  await authkit.signOut();
}
```

## Make API calls

After the user authenticates with WorkOS and connects their email, you can use the WorkOS token to make Nylas API requests. Pass the token as a Bearer token and include the `X-Nylas-External-User-Id` header with the user's `sub` claim from the JWT:

```ts
function parseSubFromJwt(token: string): string | null {
  try {
    const base64Payload = token.split(".")[1];
    const payload = JSON.parse(atob(base64Payload));
    return payload?.sub || null;
  } catch {
    return null;
  }
}

async function fetchEmails() {
  const token = await authkit.getToken();
  const userId = parseSubFromJwt(token || "");

  const response = await fetch(
    `https://api.us.nylas.com/v3/grants/me/messages`,
    {
      headers: {
        Authorization: `Bearer ${token}`,
        "X-Nylas-External-User-Id": userId || "",
      },
    },
  );

  return await response.json();
}
```

> **Info:** 
> Use `https://api.us.nylas.com` for US-hosted applications or `https://api.eu.nylas.com` for EU-hosted applications.

## Things to know about WorkOS

- **Enterprise SSO**: WorkOS supports SAML and OIDC SSO connections out of the box. If your customers use Okta, Azure AD, or other enterprise identity providers, WorkOS handles the federation layer for you.
- **Directory sync**: WorkOS can sync user directories from providers like Okta, Azure AD, and Google Workspace. This is useful if you need to pre-provision Nylas grants for users before they sign in.
- **AuthKit UI**: WorkOS provides a hosted authentication UI through AuthKit, so you don't need to build login forms. The `signIn()` method redirects to this hosted UI.
- **Token refresh**: AuthKit handles token refresh automatically. The `getToken()` method returns a valid token, refreshing it if necessary.

## What's next

- [WorkOS + Nylas Connect with React](/docs/v3/auth/nylas-connect-react/use-external-idp/workos/) for React-based implementations
- [Session management](/docs/v3/auth/nylas-connect/use-external-idp/#session-management) for monitoring connection state
- [Error handling](/docs/v3/auth/nylas-connect/use-external-idp/#error-handling) for handling authentication failures
- [Nylas Connect overview](/docs/v3/auth/nylas-connect/) for standalone OAuth without an IDP