Version:
Only show these results:

Using the Node.js SDK

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.

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

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   

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.

import Nylas from "nylas";

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 (Oregon) https://api.us.nylas.com
Europe (Ireland) http://api.eu.nylas.com

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

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

import Nylas from "nylas"

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

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

🔍 The base API URL defaults to the Nylas U.S. region. See the data residency documentation for more information.

Test Node.js SDK installation

💡 Nylas recommends 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.

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.

import 'dotenv/config'
import Nylas from 'nylas'

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

const nylas = new Nylas(NylasConfig)

const applicationDetails = await nylas.applications.getDetails()

console.log({ applicationDetails })

Authenticate end 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.

In practice, Nylas' REST API simplifies the OAuth process to two steps: redirecting the end user to Nylas, and handling the auth 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 end 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 end 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.
The order of the prompts affects the UI of the Hosted login page.

If provider is not set, the end 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.

Use this field for Microsoft admin consent credential IDs only.

Redirect end user to Nylas

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

import 'dotenv/config';
import express from 'express';
import Nylas from 'nylas';

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

🔍 Nylas provides granular auth scopes that allow you to control the level of access your application has to end users' data. For a list of scopes that Nylas supports, see the Authentication scopes documentation.

Handle the authentication response

After the end user is authenticated, Nylas redirects them to your application'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.

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.

Model and method reference

The Nylas Node.js SDK includes method and model documentation, so you can easily find the implementation details you need.

GitHub repositories

The Nylas Node.js SDK repository 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.

Tutorials