# Integrate Google Identity with Nylas Connect

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

Google Identity Services (GIS) provides OAuth 2.0 authentication for Google accounts. This guide shows you how to use Google as your identity provider with Nylas Connect so your users can sign in with their Google account and connect their email through Nylas.

The Google integration differs slightly from other IDPs because Google Identity Services returns a credential (ID token) directly rather than an access token from an SDK method. You store this credential and pass it to Nylas Connect.

## Before you begin

You need a Google Cloud OAuth 2.0 client and a Nylas application configured to work together.

> **Info:** 
> **The Google Cloud OAuth client on this page is for Google Sign-In only.** The email connection still runs through Nylas Hosted OAuth via your [Nylas Google connector](/docs/provider-guides/google/create-google-app/) — that's a separate set of Google OAuth credentials. The [Nylas Shared GCP App](/docs/provider-guides/google/shared-gcp-app/) — an add-on for Nylas Contract plans — lets you skip the connector-side GCP setup and Google verification entirely.


### 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 Google Cloud

1. In the [Google Cloud Console](https://console.cloud.google.com/), navigate to **APIs & Services** → **Credentials**.
2. Create or select an OAuth 2.0 Client ID.
3. Configure the following settings:
   - **Application type**: Select "Web application"
   - **Authorized JavaScript origins**: Add your application's origins (e.g., `http://localhost:3000`, `https://yourapp.com`)
   - **Authorized redirect URIs**: Add your application's callback URLs (e.g., `http://localhost:3000`, `https://yourapp.com`)
4. Save your Client ID for use in your application.

> **Local development setup:** 
> The code examples use `http://localhost:3000` as the redirect URI. If your app runs on a different port:
> 
> - Update the **Authorized JavaScript origins** and **Authorized redirect URIs** in Google Cloud Console
> - Update the `redirectUri` in your Nylas Connect configuration
> - Update the **Allowed Origins** and **Callback URIs** in your Nylas Dashboard's Identity Provider settings
> 
> For Google OAuth, the origins and redirect URIs must match exactly, including the protocol (`http://` for localhost).

### Load the Google Identity Services library

Add this script tag to your HTML:

```html
<script src="https://accounts.google.com/gsi/client" async defer></script>
```

No npm package is required for the vanilla JavaScript integration. The library loads from Google's CDN.

## Implementation

Initialize Google Sign-In and Nylas Connect together. Unlike other IDPs, Google Identity Services provides a credential through a callback rather than an SDK method, so you store it and return it from `identityProviderToken`:

```ts


let googleCredential: string | null = null;

function initializeGoogleSignIn() {
  google.accounts.id.initialize({
    client_id: "<GOOGLE_CLIENT_ID>",
    callback: handleGoogleResponse,
  });

  google.accounts.id.renderButton(
    document.getElementById("googleSignInButton"),
    { theme: "outline", size: "large" },
  );
}

function handleGoogleResponse(response: any) {
  googleCredential = response.credential;
  localStorage.setItem("google_credential", googleCredential);
  console.log("Google authentication successful");
}

const nylasConnect = new NylasConnect({
  clientId: "<NYLAS_CLIENT_ID>",
  redirectUri: "http://localhost:3000/auth/callback",
  identityProviderToken: async () => {
    try {
      return localStorage.getItem("google_credential");
    } catch {
      return null;
    }
  },
});

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

async function logout() {
  await nylasConnect.logout();
  google.accounts.id.disableAutoSelect();
  localStorage.removeItem("google_credential");
  googleCredential = null;
}
```

> **Info:** 
> Passing `provider: "google"` to the `connect()` method tells Nylas to expect a Google ID token and skips the provider selection screen.

## Make API calls

After the user signs in with Google and connects their email, use the stored credential to make Nylas API requests. The Google ID token contains the user's `sub` claim which you pass as the `X-Nylas-External-User-Id`:

```ts
function parseJwt(token: string): any {
  try {
    const base64Payload = token.split(".")[1];
    return JSON.parse(atob(base64Payload));
  } catch {
    return {};
  }
}

async function fetchEmails() {
  const token = localStorage.getItem("google_credential");
  const payload = parseJwt(token || "");
  const userId = payload.sub;

  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 Google Identity Services

- **Token type**: Google Identity Services returns an ID token (JWT), not an OAuth access token. This token contains user profile claims like `sub`, `email`, and `name`.
- **Token lifetime**: Google ID tokens expire after about one hour. The `google.accounts.id` library does not automatically refresh them. You may need to re-prompt the user or use the `google.accounts.id.prompt()` method.
- **One Tap sign-in**: You can enable Google One Tap for a smoother sign-in experience by calling `google.accounts.id.prompt()` after initialization.
- **Credential storage**: The example above stores the credential in `localStorage`. For production apps, consider your security requirements around client-side token storage.

## What's next

- [Google + Nylas Connect with React](/docs/v3/auth/nylas-connect-react/use-external-idp/google/) for React-based implementations using `@react-oauth/google`
- [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