Only show these results:

Authenticate users with the Nylas Node.js SDK

The Nylas REST API uses server-side OAuth, and the Node.js bindings provide convenience methods that simplify the OAuth process. Learn more about how to authenticate users with Nylas.

What you'll learn

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

  • Redirect users to Nylas.
  • Handle the authentication response.

Prerequisites

Supported properties

urlForAuthentication() takes an options object that must have a redirectURI property defined.

The following are optional properties:

Property Description
loginHint The user's email address, if known.
state An arbitrary string that will be returned back as a query param in your redirectURI.
scopes An array of which scopes you'd like to auth with. The Nylas API provides granular authentication scopes that empower users with control over what level of access your application has to their data. We provide a Scope enum that represent all the possible authentication scopes. For a full list of scopes and details behind the scopes, refer to Authentication Scopes. If omitted, defaults to all scopes.
provider A string that represents a provider to try and force authentication againist a different provider. We provide a NativeAuthenticationProvider enum that represents all the different providers that Nylas supports.

Step 1: Redirect users to Nylas

const Nylas = require('nylas');

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

router.get('/connect', (req, res, next) => {
options = {
redirectURI: 'http://localhost:3000/oauth/callback',
scopes: [Scope.EmailReadOnly, Scope.EmailSend],
};
res.redirect(Nylas.urlForAuthentication(options));
});

Step 2: Handle the authentication response

router.get('/oauth/callback', (req, res, next) => {
if (req.query.code) {
Nylas.exchangeCodeForToken(req.query.code).then(token => {
// Save the token to the current session, save it to the user model, etc.
});
} else if (req.query.error) {
res.render('error', {
message: req.query.reason,
error: {
status:
'Please try authenticating again or use a different email account.',
stack: '',
},
});
}
});

What's next?