Version:
Only show these results:

Upgrade v6 Nylas Node.js SDK to v7

Version 7.0.0 of the Nylas Node.js SDK is a major release that makes the SDK compatible with Nylas 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 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.

⚠️ 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.

Changes to v7 Node.js SDK

The new v7 Node.js SDK is a major release and brings a lot of changes. The following sections describe the updates.

Initialization changes in v7 Node.js SDK

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

First, the 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.

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.

Changes to models in v7 Node.js SDK

The v7 Node.js SDK includes specific models for each outgoing call to the Nylas APIs. 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.

For example, the v6 Node.js SDK included only one Calendar object which represented a calendar in all of the following states:

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

This meant that models 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 SDK splits 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 snippets below show how you can use each of the new models, with the equivalent commands in the v6 Node.js 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",
description: "This is my calendar", // Optional
location: "My calendar location", // Optional
timezone: "America/New_York", // Optional
}

const updateCalendarRequest: UpdateCalenderRequest = {
name: "My Updated Calendar", // All fields are optional since we're updating.
hexColor: "#000000", // Other fields not present during creation are now available.
}
const Nylas = require('nylas');
Nylas.config({clientId: '<NYLAS_CLIENT_ID>', clientSecret: '<NYLAS_CLIENT_SECRET>'});
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();

Changes to authentication in v7 Node.js SDK

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

While you can only create and manage your Nylas application's connectors (previously called "integrations") from the v3 Dashboard, you can manage almost everything else directly from the v7 Node.js SDK. This includes grants, authentication callback URIs ("redirect URIs"), and OAuth tokens, and authenticating your end users.

The v7 Node.js SDK offers two main methods for authenticating end 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. The response also includes information about the grant that was created.

💡 You don't need to use a grant ID to make a request. Instead, you can use the email address associated with a grant as the identifier. If you prefer to use the grant ID, you can extract it from the CodeExchangeResponse and use it in your future requests.

The following examples show how to authenticate an end user in the v7 Node.js SDK, and in the v6 SDK for reference.

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: "<CALLBACK_URI>",
loginHint: "anna@example.com"
});

// 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: "<CALLBACK_URI>",
clientId: "<NYLAS_CLIENT_ID>",
clientSecret: "<NYLAS_CLIENT_SECRET>",
code: "<AUTH_EXCHANGE_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: "anna@example.com",
});

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: '<NYLAS_CLIENT_ID>',
clientSecret: '<NYLAS_CLIENT_SECRET>'
});

// Build the URL for authentication.
const authUrl = Nylas.urlForAuthentication({
loginHint: body.email_address,
redirectURI: (<CALLBACK_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));

Changes to requests in v7 Node.js SDK

You might notice some new concepts in the v7 Node.js SDK when you make requests:

These are explained in more detail in the following sections.

Resource parameters

In the v7 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 account's grant ID or 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 sample. The v6 method is included as well, for reference.

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: "<NYLAS_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 v3 Nylas APIs include standard response objects for all requests, except those made to OAuth endpoints. 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

The v3 Nylas APIs include standard error objects for all requests. The v7 Node.js SDK includes two superclass error classes:

  • 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 v7 Node.js SDK

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

Because of this change, the v7 Node.js SDK 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. The code snippet below demonstrates both methods.

// Get a list of calendars.
const calendars = nylas.calendars.list({
identifier: '<NYLAS_GRANT_ID>',
});

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

// 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));   

Upgrade to v7 Node.js SDK

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

To upgrade the 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 object

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 APIs. Before you can make any API requests, you must initialize the Nylas object.

Previously, you initialized the Nylas object using your client ID, client secret, and access token. In the v7 Node.js SDK, you initialize the object using your API key and API URI. The following examples show the command you use with the v7 Node.js SDK, and with the v6 SDK for reference.

import Nylas from "nylas";

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

Nylas.config({
clientId: "<NYLAS_CLIENT_ID>",
clientSecret: "<NYLAS_CLIENT_SECRET>"
});

const nylas = Nylas.with("<NYLAS_ACCESS_TOKEN>");

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

Make requests to the Nylas APIs

To make requests to the Nylas APIs, use the Nylas instance that you initialized during setup.

The v7 Node.js SDK is organized into resources corresponding to each of the Nylas APIs. Each resource includes all of the available methods to make requests to a specific API. For example, to get a list of calendars, you can use the calendars.list method.

The code samples below show how to list calendars in the v7 Node.js SDK, and how you would do so in the v6 SDK 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: "<NYLAS_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

What's next?