Only show these results:

Get Started with the Nylas Node.js SDK

The Nylas Node.js SDK provides the quickest way to build your Email, Calendar, and Contacts integrations using JavaScript.

What you'll learn

In this tutorial, you'll learn how to do the following tasks:

  • Install the Nylas Node.js SDK.
  • Initialize the Nylas object.
  • Change the base API URL.
  • Make requests using the Node.js SDK.

Prerequisites

Before you start with the Node.js SDK, you must complete some prerequisite tasks:

Step 1: Install the Nylas Node.js SDK

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

npm install nylas   
yarn add nylas   

Step 2: 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 client ID, client secret, and access token:

  1. Call the .config() function and pass your <CLIENT_ID> and <CLIENT_SECRET>.
  2. Call the .with() function and pass your <ACCESS_TOKEN>.

All together, your code should look like the example below.

const Nylas = require('nylas');

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

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

Step 3: (Optional) Change the base API URL

You can choose to change the base API URL depending on your location:

Location API URL Scheduler API URL
United States (Oregon) https://api.nylas.com https://api.schedule.nylas.com
Europe (Ireland) https://ireland.api.nylas.com https://ireland.api.schedule.nylas.com

For more information, see Data residency and Migration guide for data centers.

If you're using the Node.js SDK v6.x and the Nylas API v3 Beta: The EU region is currently not available.

To change the API URL, pass the API_URL parameter to Nylas.config():

const Nylas = require('nylas');

Nylas.config({
clientId: <CLIENT_ID>,
clientSecret: <CLIENT_SECRET>,
apiServer: regionConfig[Region.Ireland].nylasAPIUrl
});

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

If you're using the Nylas EU region: The base API URL defaults to the US region, but you can specify apiServer: regionConfig[Region.Ireland].nylasAPIUrl to use the EU region. See Data Residency for more information.

Step 4: Test your installation

Nylas recommends that you use environment variables in your production environment. To learn more, see the official How to read environment variables guide from the Node.js team.

To test your installation, make a request to return your account details as in the example below.

const Nylas = require('nylas');

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

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

nylas.account.get().then(account => console.log(account));

Nylas returns a response similar to the one below.

{  
id: '5tgncdmczat02216u7d6uypyi',
object: 'account',
accountId: '5tgncdmczat02216u7d6uypyi',
name: 'Katherine Johnson',
emailAddress: '[email protected]',
provider: 'gmail',
organizationUnit: 'label',
syncState: 'running',
linkedAt: 2020-12-14T18:10:14.000Z
}

Use cases

The following sections describe common tasks that you can perform using the Node.js SDK.

Callbacks

Every resource method accepts an optional callback as the last argument, as in the following example.

nylas.threads.list({}, (err, threads) => {
console.log(threads.length);
});

Promises

Every resource method returns a promise, so you don't have to use callbacks if your code is promise-friendly.

nylas.threads.list({}).then(threads => {
console.log(threads.length);
});

async and await

You can also use async and await for asynchronous code, as in the example below.

const getThreadCount = async nylas => {
const threads = await nylas.threads.list({});
return threads.length;
};

Make a request without an access token

Because some API endpoints access application-level information only, they don't need an access token for requests. If you know you don't need any account information from the endpoint, you can skip adding the access token parameter.

const Nylas = require('nylas');

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

// Return all accounts connected to your Nylas application.
Nylas.accounts.list().then(accounts => {
for (let account of accounts) {
console.log(
`Email: ${account.emailAddress} | `,
`Billing State: ${account.billingState} | `,
`Sync State: ${account.syncState}`,
`ID: ${account.id} | `
);
}
});

For more information about accounts and their parameters, see the Accounts endpoint documentation.

View messages and threads

You can use the Node.js SDK to return email messages and threads from a user's email inbox, as in the following example.

const Nylas = require('nylas');

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

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

// Get the most recent email message.
nylas.messages.first({in: 'inbox'}).then(message =>{
console.log(message.subject);
// Log the Nylas global ID for the message
console.log(message.id);
// Log the service provider ID of the message
console.log(message.unread);
});

// Return the 10 most recent email threads.
nylas.threads.list({limit: 10}).then(threads =>{
for (let thread of threads) {
console.log(thread.subject);
console.log(thread.participants);
}
});

// List the 5 most recent unread email threads.
nylas.threads.list({unread: true, limit: 5}).then(threads =>{
for (let thread of threads) {
console.log(thread.subject);
}
});

You can review the following documentation to learn more about messages and threads:

  • If you're using the Nylas Node.js SDK v6.x or earlier, see the Messages and Threads endpoint documentation for more information.
  • If you're using the Nylas Node.js SDK v7.x or later, see the API v3 Messages endpoint documentation instead.

For more information on the Nylas Email API, see the Email API documentation.

Search messages and threads

Along with returning email messages and threads, you can also search a user's inbox using specific parameters. This allows you to return either individual messages or threads that match the search criteria, as in the following code sample.

const Nylas = require('nylas');

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

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

nylas.messages.search("from:[email protected]").then(messages => {
for (let message of messages) {
console.log(message.subject);
}
});

nylas.threads.search("A really important thing").then(threads => {
for (let thread of threads) {
console.log(thread.subject);
}
});

See the Search endpoint documentation for more information. If you want to learn more about the Nylas Email API, see the Email API documentation.

Create an Event

You can use the Node.js SDK to create an Event and send it to a list of participants.

const Nylas = require('nylas');

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

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

const event = new Event(nylas, {
title: 'New Years Party!',
// The user must have Write access to the Calendar you specify with the calendarID.
calendarId: <CALENDAR_ID>,
// Event times use UTC timestamps.
// This example creates an event on December 31, 2018.
when: { startTime: 1546290000, endTime: 1546300800 },

// Participants are stored as an array of participant subobjects.
participants: [{ email: '[email protected]', name: 'My Nylas Friend' }],
location: 'My House!'
});

// Event notification emails are not sent by default.
// Enable notify_participants to send an email notification to participants.
event.save({ notify_participants: true }).then(event => {
console.log(event);
});

For more information, see the Calendar and Events endpoints. To learn more about the Nylas Calendar API, see the Calendar API documentation.

Create and update webhooks

You can use the Node.js SDK to both create and update webhooks.

const Nylas = require('nylas');

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

// Create a new webhook.
const newWebhook = new Webhook(nylas, <CLIENT_ID>, {
callbackUrl: 'https://wwww.myapp.com/webhook',
state: 'active',
triggers: ['event.created', 'event.updated'],
});
newWebhook.save().then(webhook => console.log(webhook.id));

// Get and update the state of an existing webhook.
// Note: a webhook's callbackUrl & triggers cannot be updated, only its state.
Nylas.webhooks.find('existingWebhookId').then(existingWebhook => {
existingWebhook.state = 'active';
existingWebhook.save();
})

// Delete an existing webhook.
Nylas.webhooks.delete(existingWebhook);

What’s next?