# Integrate Auth0 with Nylas Connect

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

Auth0 is an enterprise authentication platform that supports social logins, passwordless authentication, MFA, and SSO. This guide shows you how to use Auth0 as your identity provider with Nylas Connect so your users can authenticate with Auth0 and connect their email accounts through Nylas.

## Before you begin

You need an Auth0 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 Auth0

1. In your [Auth0 Dashboard](https://manage.auth0.com/), navigate to **Applications** → **Applications**.
2. Select your application or create a new Single Page Application.
3. Configure the following settings:
   - **Allowed Callback URLs**: Add your application's callback URLs (e.g., `http://localhost:3000`, `https://yourapp.com`)
   - **Allowed Web Origins**: Add your application's origins (e.g., `http://localhost:3000`, `https://yourapp.com`)
   - **Allowed Logout URLs**: Add URLs where users can be redirected after logout

> **Local development setup:** 
> If you're running your app on a different port (e.g., `http://localhost:5173` for Vite), make sure to update:
> 
> - The URLs in your Auth0 Dashboard settings above
> - The `redirect_uri` in your Auth0 client configuration
> - The `redirectUri` in your Nylas Connect configuration
> - The **Allowed Origins** in your Nylas Dashboard's Identity Provider settings
> 
> All these URLs must match exactly for authentication to work correctly.

### Install dependencies

```bash
npm install @nylas/connect @auth0/auth0-spa-js
```

## Implementation

Initialize Auth0 and Nylas Connect together. The `identityProviderToken` callback passes the Auth0 token to Nylas Connect so it can associate the user's identity with their Nylas grant:

```ts


const auth0 = new Auth0Client({
  domain: "<AUTH0_DOMAIN>",
  clientId: "<AUTH0_CLIENT_ID>",
  authorizationParams: {
    redirect_uri: window.location.origin,
  },
});

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

async function loginWithAuth0() {
  await auth0.loginWithPopup();
  const isAuthenticated = await auth0.isAuthenticated();

  if (isAuthenticated) {
    const user = await auth0.getUser();
    console.log("Authenticated as:", user?.email);
  }
}

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 auth0.logout({
    logoutParams: { returnTo: window.location.origin },
  });
}
```

## Make API calls

After the user authenticates with Auth0 and connects their email, you can use the Auth0 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 auth0.getTokenSilently();
  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.

## What's next

- [Auth0 + Nylas Connect with React](/docs/v3/auth/nylas-connect-react/use-external-idp/auth0/) 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