# Using the Node.js SDK

Source: https://developer.nylas.com/docs/v3/sdks/node/

The Nylas Node.js SDK is an open-source software development kit that enables you to use JavaScript to integrate the Nylas APIs with your application.


> **Warn:** 
> ⚠️ **The v7.x Nylas Node.js SDK is only compatible with v3.x Nylas APIs**. If you're still using an earlier version Nylas, you should keep using the v6.x Node.js SDK until you can upgrade to Nylas v3.


## Before you begin

Before you can start using the Nylas Node.js SDK, make sure you have done the following:

- [Create a free Nylas developer account](https://dashboard-v3.nylas.com/register?utm_source=docs&utm_medium=devrel-surfaces&utm_campaign=&utm_content=node-sdk).
- [Get your developer keys](/docs/dev-guide/dashboard/#get-your-api-key). You need to have your...
  - `NYLAS_API_KEY`: The API key for your application in the Nylas Dashboard.
  - `NYLAS_API_URI`: The URI for your application according to your [data residency](/docs/dev-guide/platform/data-residency/)
  - `NYLAS_GRANT_ID`: The grant ID provided when you authenticate an account to your Nylas application.
- Install [Node.js](https://nodejs.org/).
- Install either [npm](https://www.npmjs.com/) or [yarn](https://yarnpkg.com/).

## Install the Nylas Node.js SDK

You can install the Nylas Node.js SDK using either `npm` or `yarn`.

```bash
npm install nylas
```

```bash
yarn add nylas
```

## Initialize the Nylas object

The `Nylas` object provides access to every resource in the Nylas API. Before you make any API requests, you must initialize the `Nylas` object with your API key and API URI.

```js


const nylas = new Nylas({
  apiKey: "<NYLAS_API_KEY>",
  apiUri: "<NYLAS_API_URI>",
});
```

## (Optional) Change the base API URL


You can choose to change the base API URL depending on your location, as in the table below.

| Location               | Nylas API URL              |
| ---------------------- | -------------------------- |
| United States (Iowa)   | `https://api.us.nylas.com` |
| Europe (London)        | `https://api.eu.nylas.com` |

For more information, see our [data residency documentation](/docs/dev-guide/platform/data-residency/).


To change the API URL, pass the `API_URI` parameter to `new Nylas(NylasConfig)`.

```js


const NylasConfig = {
  apiKey: "<NYLAS_API_KEY>",
  apiUri: "<NYLAS_API_URI>",
};

const nylas = new Nylas(NylasConfig);
const applicationDetails = await nylas.applications.getDetails();
```

> **Info:** 
> **The base API URL defaults to the Nylas U.S. region**. See the [data residency documentation](/docs/dev-guide/platform/data-residency/) for more information.

## Test Node.js SDK installation

> **Success:** 
> 💡 **Nylas recommends you use environment variables in your production environment**. To learn more, see the official [How to read environment variables guide](https://nodejs.org/en/learn/command-line/how-to-read-environment-variables-from-nodejs) from the Node.js team.

Now that you have the Node.js SDK installed and set up, you can make a simple program to test your installation. For example, the following code makes a request to return information about your Nylas application.

```js

import Nylas from "nylas";

const nylas = new Nylas({
  apiKey: "<NYLAS_API_KEY>",
  apiUri: "<NYLAS_API_URI>",
});

const applicationDetails = await nylas.applications.getDetails();

console.log({ applicationDetails });


```

## Authenticate users

The Nylas APIs use OAuth 2.0 and let you choose to authenticate using either an API key or access token. For more information about authenticating with Nylas, see the [Authentication guide](/docs/v3/auth/).

In practice, Nylas' REST API simplifies the OAuth process to two steps: [redirecting the user to Nylas](#redirect-user-to-nylas), and [handling the auth response](#handle-the-authentication-response).

### Supported properties

In Nylas, `urlForOAuth2` takes a set of properties that must include a `redirectUri`. You may also pass the optional properties listed in the table below.

| Property                | Description                                                                                                                                                                                                                                                                                                      |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `loginHint`             | The user's email address.                                                                                                                                                                                                                                                                                        |
| `state`                 | An arbitrary string that is returned as a query parameter in your `redirectUri`.                                                                                                                                                                                                                                 |
| `scope`                 | A space-delimited list of scopes that identify the resources that your application may access on the user's behalf. If no scopes are set, Nylas uses the default connector scopes.                                                                                                                               |
| `provider`              | The provider you want to authenticate with.                                                                                                                                                                                                                                                                      |
| `prompt`                | The prompt for the Hosted login page. This parameter can accept comma separated values without spaces in between.<br /> The order of the prompts affects the UI of the Hosted login page.<br /><br /> If `provider` is not set, the user is redirected to the provider page directly, and the prompt is ignored. |
| `access_type`           | Specifies if Nylas should return a refresh token with the exchange token. This isn't suitable for client-side or JavaScript applications.                                                                                                                                                                        |
| `code_challenge`        | Specifies a Base64-encoded `code_verifier` without padding. The verifier is used as a server-side challenge during the authorization code exchange.                                                                                                                                                              |
| `code_challenge_method` | Specifies the method used to encode the `code_verifier`. The verifier is used as a server-side challenge during the authorization code exchange.                                                                                                                                                                 |
| `credential_id`         | (Microsoft admin consent bulk authentication flow only) The ID of an existing Nylas connector credential record that's attached to the application's Microsoft connector.<br /><br /> Use this field for Microsoft admin consent credential IDs only.                                                            |

### Redirect user to Nylas

To redirect your users to Nylas, first initialize the `Nylas` object and set your redirect options. You'll need your application's callback URI and all scopes that your project uses. The example below shows how to use this information to set up a redirect.

```js


const AuthConfig = {
  clientId: process.env.NYLAS_CLIENT_ID as string,
  redirectUri: "http://localhost:3000/oauth/exchange",
};

const NylasConfig = {
  apiKey: process.env.NYLAS_API_KEY as string,
  apiUri: process.env.NYLAS_API_URI as string,
};

const nylas = new Nylas(NylasConfig);

app.get('/nylas/auth', (req, res) => {
  const authUrl = nylas.auth.urlForOAuth2({
    clientId: AuthConfig.clientId,
    provider: 'google',
    redirectUri: AuthConfig.redirectUri,
    loginHint: '<USER_EMAIL>',
    scope: ['email']
  })

  res.redirect(authUrl);
});
```

> **Info:** 
> **Nylas provides granular scopes that allow you to control the level of access your application has to users' data**. For a list of scopes that Nylas supports, see [Using granular scopes to request user data](/docs/dev-guide/scopes/).

### Handle the authentication response

After the user is authenticated, Nylas redirects them to your project's callback URI. If the auth process is successful, Nylas includes a `code` as a query parameter. The example below shows how to handle the response and anticipate any errors.

```js
app.get("/oauth/callback", async (req, res) => {
  const code = req.query.code;

  if (!code) {
    res.status(400).send("No authorization code returned from Nylas");
    return;
  }

  try {
    const response = await nylas.auth.exchangeCodeForToken({
      clientSecret: config.clientSecret,
      clientId: config.clientId,
      code,
      redirectUri: config.redirectUri,
    });

    const { grantId } = response;

    console.log({ grantId });
    res.status(200).send({ grantId });
  } catch (error) {
    console.error("Error exchanging code for token:", error);
    res.status(500).send("Failed to exchange authorization code for token");
  }
});
```

## Latest supported version

For the latest supported version of the SDK, see the [Releases page on GitHub](https://github.com/nylas/nylas-nodejs/releases).

## Model and method reference

The Nylas Node.js SDK includes [method and model documentation](https://nylas-nodejs-sdk-reference.pages.dev/), so you can easily find the implementation details you need.

## GitHub repositories

The [Nylas Node.js SDK repository](https://github.com/nylas/nylas-nodejs) houses the Node.js SDK. You can contribute to the SDK by creating an issue or opening a pull request.

For Nylas code samples, visit the [Nylas Samples repository](https://github.com/nylas-samples).

## Tutorials

- [Read messages and threads](/docs/v3/sdks/node/read-messages-threads/)
- [Send messages](/docs/v3/sdks/node/send-email/)
- [Manage inbox labels and folders](/docs/v3/sdks/node/manage-folders-labels/)
- [Manage events](/docs/v3/sdks/node/manage-events/)
- [Manage contacts](/docs/v3/sdks/node/manage-contacts/)

## Recipes in the Cookbook

The [Nylas Cookbook](/docs/cookbook/) has task-focused recipes with examples in Node.js and every other SDK language. A few good starting points:

- [Send transactional email](/docs/cookbook/email/transactional-send/)
- [Schedule a message to send later](/docs/cookbook/email/schedule-send/)
- [Create and manage drafts](/docs/cookbook/email/manage-drafts/)
- [Organize folders and labels](/docs/cookbook/email/organize-folders/)
- [Reply to a thread](/docs/cookbook/email/threads/reply-to-a-thread/)
- [Work with the Contacts API](/docs/cookbook/contacts/contacts-api-guide/)