Authenticate users with the Nylas Node.js SDK
The Nylas REST API uses server-side OAuth, and the bindings included in the Node.js SDK provide convenient ways to simplify the OAuth process. For more information about OAuth and other user authentication methods, see our Authentication docs.
What you'll learn
In this tutorial, you'll learn how to do the following tasks:
- Redirect users to Nylas.
- Handle authentication responses.
Prerequisites
Before you start, follow our Get Started with the Node.js SDK guide.
Supported properties
The urlForAuthentication()
method takes an options
object that must have a redirectURI
defined. You may also pass these optional properties:
Property | Description |
---|---|
loginHint |
The user's email address, if known. |
state |
An arbitrary string that will be returned as a query parameter in your redirectURI . |
scopes |
An array of scopes that you want to authenticate with. If omitted, Nylas includes all scopes by default. 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 represents all the possible authentication scopes. For a full list of scopes and their details, see Authentication Scopes. |
provider |
A string representing a provider that you want to try to force authentication against. The Nylas API provides a NativeAuthenticationProvider enum that represents all supported providers. |
Step 1: Redirect users to Nylas
To redirect your users to Nylas, initialize the Nylas
object and set your redirect options. You'll need your callback URI (redirectURI
) and all scopes that your project uses. The code sample below demonstrates how to use this information to set up a redirect:
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
After your user is redirected and authenticated, Nylas redirects them back to your application's callback URI. If the authentication was successful, code
is included as the query parameter. The code snippet below shows how to handle the response and anticipate any errors.
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?
- Follow our Node.js SDK tutorials.