Only show these results:

Upgrade the Nylas Node.js SDK from v6 to v7

Version 7.0.0 of the Nylas Node.js SDK is a major release compatible with Nylas API v3. The goal of this release was to make the SDK more intuitive and easier to use. It includes method and model documentation, so you can easily find the implementation details that you need.

Nylas API v3 brings a lot of changes. Be sure to familiarize yourself with them before you start upgrading. For more information, see the list of v3 features and changes and the v3 diff list.

⚠️ v7 of the Nylas Node.js SDK is not compatible with APIs earlier than v3. If you're still using an earlier version of the Nylas API for your project, Nylas recommends that you keep using v6.x of the Node.js SDK until you can start using the v3 APIs.

Upgrade to Nylas Node.js SDK v7

📝 Note: The minimum Node.js version is now the lowest-supported long-term stable release (LTS): v16.

To upgrade a v6.x Nylas Node.js SDK to v7, use either npm or yarn to download and install the new version.

npm install nylas@7   
yarn add nylas@7   

Initialize the Nylas SDK

After you upgrade to v7 of the SDK, you need to set up your environment.

The Nylas object provides access to every resource in the Nylas API. Before you make any API requests, you must initialize the Nylas object.

Previously you initialized the Nylas object with your client ID, client secret, and access token. For v3, initialize the Nylas object with your API key and API URI.

import Nylas from "nylas";

const nylas = new Nylas({
apiKey: "NYLAS_API_KEY", // Required to make API calls.
apiUri: "NYLAS_API_URI", // Required to make API calls.
})
const Nylas = require('nylas');

Nylas.config({
clientId: <CLIENT_ID>,
clientSecret: <CLIENT_SECRET>
});

const nylas = Nylas.with(<ACCESS_TOKEN>);

You can now use the Nylas instance to make API requests.

Initialization changes in the Node.js SDK v7

You may notice a few changes in the code to initialize the Nylas SDK.

First, the Nylas SDK is now a hybrid Node project, meaning it uses both CommonJS and ES6 modules. This means that you can import the Nylas SDK using either require or import.

Second, the Nylas SDK entry point is no longer static. Instead of importing the SDK directly, you import the Nylas class from the SDK. This allows you to create multiple instances of the Nylas SDK, each with their own configuration.

Model changes in the Node.js SDK v7

v7 of the Nylas Node.js SDK includes specific models for each outgoing call to the Nylas API. This change is designed to make it easier to work with the SDK.

Models have also been changed from classes to TypeScript interfaces, and all functions that made API calls have been removed from the models. This means that models are now purely data structures.

Example: Calendar models

In v6.x of the Nylas Node.js SDK, only one Calendar object was available. It simultaneously represented a Calendar in the following states:

  • To be created.
  • To be updated.
  • To be retrieved.

This meant that models like the Calendar model had to be configured with all possible fields that could ever be used in any of the above scenarios. This made objects very large and difficult to anticipate as a developer.

v7 of the Node.js SDK has split the Calendar model into three:

  • Calendar: A model for retrieving a Calendar object.
  • CreateCalendarRequest: A model for creating a Calendar object.
  • UpdateCalendarRequest: A model for updating a Calendar object.

The code snippet below demonstrates how you can use each of these new models, with the equivalent commands in the old v6 Node SDK, for reference.

// Import is required only if you need the typing.
import { CreateCalendarRequest, UpdateCalendarRequest } from "nylas/lib/types/models/calendars";

const createCalendarRequest: CreateCalendarRequest = {
name: "My Calendar", // Calendar name is required.
description: "This is my calendar", // Calendar description is optional.
location: "My calendar location", // Calendar location is optional.
timezone: "America/New_York", // Calendar timezone is optional.
}

const updateCalendarRequest: UpdateCalenderRequest = {
name: "My Updated Calendar", // All fields are optional since we are updating.
hexColor: "#000000", // Other fields not present during creation are now available.
}
const Nylas = require('nylas');
Nylas.config({clientId: 'clientId', clientSecret: 'clientSecret'});
const nylas = Nylas.with('access_token');

const calendar = new Calendar(nylas, {
name: "My New Calendar",
description: "Description of my new calendar",
location: "Location description",
timezone: "America/Los_Angeles",
metadata: {
test: "true",
}
})

calendar.save();

Making requests to the Nylas API

To make requests to the Nylas API, you use the Nylas instance that you configure when you initialize the Nylas SDK.

The Nylas SDK is organized into resources corresponding to each of the Email and Calendar APIs. Each resource includes all of the available methods to make requests to a specific API.

ℹ️ Available v3 APIs: Currently, only the v3 Email and Calendar APIs are available. The Messages, Drafts, Threads, and Contacts APIs are coming soon!

For example, to get a list of Calendars, you can use the calendars.list method as in the example below. (The v6 Node SDK example is included for reference.)

import Nylas from "nylas";
import { NylasListResponse } from "nylas/lib/types/models/responses";
import { Calendar } from "nylas/lib/types/models/calendars";

const nylas = new Nylas({
apiKey: "NYLAS_API_KEY",
});

const response: NylasListResponse<Calendar> = await
nylas.calendars.list({
identifier: "GRANT_ID", // Required. The Grant ID of the account to make the request for.
});
const Nylas = require('nylas');
Nylas.config({clientId: 'clientId', clientSecret: 'clientSecret'});
const nylas = Nylas.with('access_token');

// Get all calendars found in the user's account
nylas.calendars.list().then(calendars => console.log(calendars));

// Get a count of all the users' calendars
nylas.calendars.count().then(calendarCount => console.log(calendarCount));

// Get the first calendar
nylas.calendars.first().then(calendar => console.log(calendar));

// Query calendars by metadata
nylas.calendars.list({metadata_key: "test"}).then(calendar => console.log(calendar));

// Get calendars with metadata
const calendars = await nylas.calendars.list({metadata_key: "test"});

// The following attributes are available for the Calendar object
const calendar = calendars[0];
calendar.id
calendar.object
calendar.accountId
calendar.name
calendar.description
calendar.readOnly

Changes to requests in the Node.js SDK v7

There are some new concepts in the Node.js SDK that you may notice when making requests. These are explained in more detail in the following sections.

Resource parameters

In v7 of the Nylas Node.js SDK, each resource takes different parameters.

All resources take an identifier, which is the ID of the account ("Grant") that you want to make the request for. This is usually the Grant ID associated with the account's email address.

Some resources also take query parameters, which are mainly used to filter data or pass additional information. Models are available for all of the query parameters that can be passed to a resource. For example, you can use ListCalendarsQueryParams as in the following code snippet.

import Nylas from "nylas";
import { NylasListResponse } from "nylas/lib/types/models/responses";
import { Calendar, ListCalendersQueryParams } from "nylas/lib/types/models/calendars";

const nylas = new Nylas({
apiKey: "NYLAS_API_KEY",
});

const queryParams: ListCalendersQueryParams = {
limit: 10
}

const response: NylasListResponse<Calendar> = await
nylas.calendars.list({
identifier: "GRANT_ID",
queryParams, // Returns a maximum of 10 Calendars.
});
const Nylas = require('nylas');
Nylas.config({clientId: 'clientId', clientSecret: 'clientSecret'});
const nylas = Nylas.with('access_token');

// Get all calendars found in the user's account
nylas.calendars.list().then(calendars => console.log(calendars));

// Get a count of all the users' calendars
nylas.calendars.count().then(calendarCount => console.log(calendarCount));

// Get the first calendar
nylas.calendars.first().then(calendar => console.log(calendar));

// Query calendars by metadata
nylas.calendars.list({metadata_key: "test"}).then(calendar => console.log(calendar));

// Get calendars with metadata
const calendars = await nylas.calendars.list({metadata_key: "test"});

// The following attributes are available for the Calendar object
const calendar = calendars[0];
calendar.id
calendar.object
calendar.accountId
calendar.name
calendar.description
calendar.readOnly

Standard response objects

The Nylas API v3 includes standard response objects for all requests, except those made to OAuth endpoints. The Node.js SDK has been updated to reflect this change with v7.

Generally, you'll encounter two types of response objects:

  • NylasResponse: Used for requests that return a single object. This returns a parameterized object of the type that you requested, and a string representing the request ID.
  • NylasListResponse: Used for requests that return a list of objects. This returns a list of parameterized objects of the type that you requested, a string representing the request ID, and a string representing the next page's token.

Standard error objects

Like the response objects, the Nylas API v3 includes standard error objects for all requests. The Nylas Node.js SDK includes two superclass error classes in v7:

  • AbstractNylasApiError: Used for errors returned by the API.
  • AbstractNylasSdkError: Used for errors returned by the SDK.

The AbstractNylasApiError class includes two subclasses:

  • NylasOAuthError: Used for API errors that are returned from OAuth endpoints.
  • NylasApiError: Used for all other Nylas API errors.

The Node.js SDK extracts error details from the request response and stores them in an error object, along with the associated request ID and HTTP status code.

Currently, the AbstractNylasSdkError class has only one subclass: the NylasSdkTimeoutError, which is thrown when a request times out.

Pagination changes in the Node.js SDK v7

Pagination has changed in the Nylas API v3. In v3, if the NylasListResponse returns more than one page of results, Nylas sends a nextCursor parameter that contains a token for the next page.

Because of this change, the Nylas Node.js SDK v7 also handles pagination differently from previous versions. There are now two ways to paginate a request: you can use the next() function to access the next page, or you can use a for await ... of loop to auto-paginate to the end of the list. Both options are demonstrated in the code snippet below.

// Get a list of Calendars.
const calendars = nylas.calendars.list({
identifier: 'Grant_ID',
});

// Option 1 - Use the next() function to get the next page.
const nextPage = await calendars.next();

// Option 2 - Use a for await...of loop to auto-paginate until the end.
for await (const item of calendars) {
// Do something with each item.
}
nylas.calendars.list({limit: 10, offset: 5}).then(calendars => console.log(calendars));   

Authentication changes in the Node.js SDK v7

The authentication methods available in the Node.js SDK v7 reflect those available in the new Nylas API v3. Nylas recommends you use OAuth and an API key, but you should make sure you understand the options before migrating.

While you can only create and manage your application's connectors (formerly known as "integrations") in the v3 Dashboard, you can manage almost everything else directly from the Node.js SDK. This includes managing Grants, auth callback URIs (redirect URIs), and OAuth tokens, and authenticating your users.

The Nylas Node.js SDK v7 offers two main methods for authenticating users to your Nylas application:

  • Auth#urlForOAuth2: Returns the redirect URL for authentication with Nylas' OAuth 2.0 implementation.
  • Auth#exchangeCodeForToken: Exchanges an authorization code that Nylas returned from an authentication redirect for an access token from the OAuth provider.

Nylas' response to the Auth#exchangeCodeForToken method includes an access token and information about the Grant that was created.

You do not need to use a grant_id to make a request. Instead, you can use a Grant's associated email address as the identifier for the account. If you prefer to use the grant_id, you can extract it from the CodeExchangeResponse object and use it.

Example: Authenticate a user

The following example demonstrates how to authenticate a user into a Nylas application.

import Nylas from "nylas";

const nylas = new Nylas({
api_key: "NYLAS_API_KEY",
});

// Build the URL for authentication.
const authURL = nylas.auth.urlForOAuth2({
clientId: "NYLAS_CLIENT_ID",
redirectUri: "REDIRECT_URI",
loginHint: "[email protected]"
});

// Write code here to redirect the user to the URL and parse the code.
...

// Exchange the code for an access token.
const codeExchangeResponse = nylas.auth.exchangeCodeForToken({
redirectUri: "REDIRECT_URI",
clientId: "NYLAS_CLIENT_ID",
clientSecret: "NYLAS_CLIENT_SECRET",
code: "CODE"
});

// Use either the email address that was authenticated or the Grant ID in the response as the identifier.
const responseWithEmail: NylasListResponse<Calendar> = await
nylas.calendars.list({
identifier: "[email protected]",
});

const responseWithGrant: NylasListResponse<Calendar> = await
nylas.calendars.list({
identifier: codeExchangeResponse.grantId,
queryParams, // Returns a maximum of 10 Calendars.
});
const Nylas = require('nylas');

Nylas.config({
clientId: '<CLIENT_ID>',
clientSecret: '<CLIENT_SECRET>'
});

// Build the URL for authentication.
const authUrl = Nylas.urlForAuthentication({
loginHint: body.email_address,
redirectURI: (CLIENT_URI || '') + body.success_url,
scopes: [Scope.EmailModify, Scope.EmailSend],
});

// Write code here to redirect the user to the URL and parse the code.

const { accessToken, emailAddress } = await Nylas.exchangeCodeForToken(
body.token
);

const nylas = Nylas.with(accessToken);

nylas.calendars.list({limit: 10, offset: 5}).then(calendars => console.log(calendars));

What's next?