Getting started with the Nylas Node.js SDK
The 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:
- Install the Nylas Node.js SDK.
- Make requests using the Node.js SDK.
Prerequisites
-
Sign up for your developer account.
-
Get your Nylas keys:
CLIENT_ID
- The CLIENT ID found on the dashboard page for your Nylas App.CLIENT_SECRET
- The CLIENT SECRET found on the dashboard page for your Nylas App.ACCESS_TOKEN
- The access token provided when you authenticate an account to your Nylas App.
-
Install Node.js.
Step 1: Install the Nylas Node.js SDK
Run one of the following commands:
npm install nylas
yarn add nylas
Step 2: Initialize the Nylas object
The Nylas
object provides access to every resource in Nylas APIs. Before making any request, you must initialize the Nylas
object with your client ID, client secret, and access token.
-
Call the
config
function and pass your client ID (<CLIENT_ID>
) and client secret (<CLIENT_SECRET>
). -
Call the
with
function and pass your access token (<ACCESS_TOKEN>
).
const Nylas = require('nylas');
Nylas.config({
clientId: <CLIENT_ID>,
clientSecret: <CLIENT_SECRET>,
});
const nylas = Nylas.with(<ACCESS_TOKEN>);
Step 3: Test your installation
In production, Nylas recommends using environment variables. Learn how to read environment variables from Node.js.
To test your installation, make a request to return your account details.
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));
The following is an example response:
{
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 are common use cases for the Nylas Node.js SDK.
Callbacks
Every resource method accepts an optional callback as the last argument.
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
.
const getThreadCount = async nylas => {
const threads = await nylas.threads.list({});
return threads.length;
};
Make a request without an access token
Some endpoints don’t need an access token since they only access application-level information. You can skip adding the access token if you don’t need account information.
const Nylas = require('nylas');
Nylas.config({
clientId: <CLIENT_ID>,
clientSecret: <CLIENT_SECRET>,
});
// Return all accounts connected to your Nylas App.
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} | `
);
}
});
Learn More
Learn more about the accounts endpoint.
View messages and threads
const Nylas = require('nylas');
Nylas.config({
clientId: <CLIENT_ID>,
clientSecret: <CLIENT_SECRET>,
});
const nylas = Nylas.with(<ACCESS_TOKEN>);
//Get the most recent 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 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);
}
});
Learn More
Learn more about the messages and threads endpoints. For more information on the functionality of the Nylas Email API, refer to Email API.
Search messages and threads
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);
}
});
Learn More
Learn more about the search endpoint. For more information on the functionality of the Nylas Email API, refer to Email API.
Create an event
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!',
// calendarID must be the ID for a calendar the user has write access to.
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);
});
Learn More
Learn more about the calendars and events endpoints. For more information on the functionality of the Nylas Calendar API, refer to Calendar API.
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 are not updateable, only its state.
Nylas.webhooks.find('existingWebhookId').then(existingWebhook => {
existingWebhook.state = 'active';
existingWebhook.save();
})
// Delete an existing webhook
Nylas.webhooks.delete(existingWebhook);