HomeLearnHow-toMongoDB Stitch Authentication Triggers

MongoDB Stitch Authentication Triggers

Updated: Apr 04, 2022 |

Published: Sep 25, 2018

  • Realm
  • Atlas
  • JavaScript
  • ...

By Andrew Morgan

Rate this article

Please note: This article discusses Stitch. Stitch is now MongoDB Realm. All the same features and functionality, now with a new name. Learn more here. We will be updating this article in due course.

MongoDB Stitch makes it a breeze to use third party services such as Google or Facebook to authenticate your app's users. This is great for your users as it means they don't need to go through the tedious process of having to provide all of their details to yet another application/service - it also means one less password to remember.

While delegating the authentication process makes your app secure and straightforward to use, you may still want to customize the process for your users. For example, if someone is registering for the first time, then you probably want to send them a welcome email. When a user deregisters, there may be regulations (such as GDPR) that mandate you delete all of their data.

This is where Stitch Authentication Triggers come to the fore. The model is very simple; you register a Stitch Function with any authentication event (register (create), login, deregister (delete)), then add JavaScript code to that function to perform the required actions.

Simply create the trigger through the Stitch UI (in this case, to send the user an email every time they log in):

Triggering a MongoDB Stitch function when user logs in

and implement the function (emailLoginNotification) that receives the authentication event and sends the email using the AWS SES service:

1exports = function(event){
2 var aws = context.services.get('AWS');
3 var input = {
4 Destination: {
5 ToAddresses: [event.user.data.email]
6 },
7 Message: {
8 Body: {
9 Html: {
10 Charset:"UTF-8",
11 Data: "This is a message to confirm that "
12 + event.user.data.name
13 + " (" + event.user.data.email
14 + ") has just logged into TrackMe"
15 }
16 },
17 Subject: {
18 Charset:"UTF-8",
19 Data: "TrackMe Login"
20 }
21 },
22 Source: context.values.get('fromEmail')
23 };
24 try {
25 aws.ses().SendEmail(input).then(function (result){
26 console.log(JSON.stringify(result));
27 });
28 } catch(error) {
29 console.log(JSON.stringify(error));
30 }

Creating your first Stitch app? Start with one of the Stitch tutorials.

Want to learn more about MongoDB Stitch? Read the white paper.

Get started with MongoDB Atlas today!

Rate this article
MongoDB logo
© 2021 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.