Triggers
Run Code on the Server in Response to Server Events.

Introduction

Triggers are a way to perform operations in response to particular server-side events such as when data is saved to a particular collection. These typically come in two flavors.
  • Before X: trigger is called before X happens.
  • After X: trigger is called after X happens.
Triggers operate against a specific collection like EthTransactions. For example, to update the status of an order object to "sold" when a particular NFT is transferred, you could define an afterSave trigger on EthNFTTransfers. The trigger would get called every time a new entry is added to the EthNFTTransfers collection, and you could check to see if it matches one of the open orders.

Unconfirmed Transactions

Transactions on Testnet and Mainnet can take a while to be confirmed. When Moralis detects a new transaction (or event) in an unconfirmed state, these get put into the collection with confirmed: false. For aggregate collections like balances, the unconfirmed transaction entries are put in separate collections post-fixed with "Pending".
  • EthBalancePending
  • EthNFTOwnersPending
  • etc.
When the transaction gets confirmed, the status is updated to confirmed: true and any corresponding entries in pending collections are merged into their respective main collections.

Consequences for Triggers

This means if you define an afterSave trigger on a collection then the trigger can get fired TWICE- once for confirmed: false and again for confirmed: true! This can happen for any collection with a "confirmed" property. Write your trigger callback function with this behavior in mind. If the trigger creates entries in other collections then this could result in duplicate entries, or double counting in calculations, etc.
The confirmed status can be checked by getting the object that fired the trigger using request.object.
1
Moralis.Cloud.afterSave("EthTransactions", async function(request) {
2
const confirmed = request.object.get("confirmed");
3
if (confirmed) {
4
// do something
5
} else {
6
// handle unconfirmed case
7
}
8
});
Copied!

Skipping Unconfirmed Transactions

It's possible to prevent unconfirmed transactions from being saved to a particular collection by defining a beforeConsume trigger.

Local Dev Chains

Ganache and Hardhat only process new blocks when a transaction is made. This means if you mint a new NFT or make a token transfer these transactions could get "stuck" in a pending table. These will get moved out of pending after one confirmation.

Tutorials

Save Triggers

beforeSave

IMPLEMENTING DATA VALIDATION

Another reason to run code in the cloud is to enforce a particular data format. For example, you might have both an Android and an iOS app, and you want to validate data for each of those. Rather than writing code once for each client environment, you can write it just once with cloud code.
Let’s take a look at our movie review example. When you’re choosing how many stars to give something, you can typically only give 1, 2, 3, 4, or 5 stars. You can’t give -6 stars or 1337 stars in a review. If we want to reject reviews that are out of bounds, we can do this with the beforeSave method:
1
Moralis.Cloud.beforeSave("Review", (request) => {
2
// do any additional beforeSave logic here
3
},{
4
fields: {
5
stars : {
6
required:true,
7
options: stars => {
8
return stars >= 1 && stars <= 5;
9
},
10
error: 'Your review must be between one and five stars'
11
}
12
}
13
});
14
Copied!
If the function throws, then the Review object will not be saved and the client will get an error. If nothing is thrown, the object will be saved normally.
One useful tip is that even if your app has many different versions, the same version of cloud code applies to all of them. Thus, if you launch an application that doesn’t correctly check the validity of input data, you can still fix this problem by adding a validation with beforeSave.

MODIFYING OBJECTS ON SAVE

In some cases, you don’t want to throw out invalid data. You just want to tweak it a bit before saving it. beforeSave can handle this case, too. Any adjustment you make to request.object will be saved.
In our movie review example, we might want to ensure that comments aren’t too long. A single long comment might be tricky to display. We can use beforeSave to truncate the comment field to 140 characters:
1
Moralis.Cloud.beforeSave("Review", (request) => {
2
const comment = request.object.get("comment");
3
if (comment.length > 140) {
4
// Truncate and add a ...
5
request.object.set("comment", comment.substring(0, 137) + "...");
6
}
7
});
Copied!

PREDEFINED CLASSES

If you want to use beforeSave for a predefined class in the Moralis JavaScript SDK, you should not pass a string for the first argument. Instead, you should pass the class itself, for example:
1
Moralis.Cloud.beforeSave(Moralis.User, async (request) => {
2
// code here
3
},
4
// Validation Object or Validation Function
5
)
Copied!

afterSave

In some cases, you may want to perform some type of action, such as a push, after an object has been saved. You can do this by registering a handler with the afterSave method. For example, suppose you want to keep track of the number of comments on a blog post. You can do that by writing a function like this:
1
Moralis.Cloud.afterSave("Comment", (request) => {
2
const query = new Moralis.Query("Post");
3
query.get(request.object.get("post").id)
4
.then(function(post) {
5
post.increment("comments");
6
return post.save();
7
})
8
.catch(function(error) {
9
console.error("Got an error " + error.code + " : " + error.message);
10
});
11
});
Copied!

ASYNC BEHAVIOR

In the example above, the client will receive a successful response before the promise in the handler completes, regardless of how the promise resolves. For instance, the client will receive a successful response even if the handler throws an exception. Any errors that occurred while running the handler can be found in the cloud code log.
You can use an afterSave handler to perform lengthy operations after sending a response back to the client. In order to respond to the client before the afterSave handler completes, your handler may not return a promise and your afterSave handler may not use async/await.

PREDEFINED CLASSES

If you want to use afterSave for a predefined class in the Moralis JavaScript SDK, you should not pass a string for the first argument. Instead, you should pass the class itself, for example:
1
Moralis.Cloud.afterSave(Moralis.User, async (request) => {
2
// code here
3
})
Copied!

Context

When saving a Moralis.Object, you may pass a context dictionary that's accessible in the Cloud Code Save Triggers. More info in the JavaScript Guide.
The context is also passed from a beforeSave handler to an afterSave handler. The following example sends emails to users who are being added to a Moralis.Role’s user relation asynchronously, so that the client receives a response before the emails complete sending:
1
const beforeSave = function beforeSave(request) {
2
const { object: role } = request;
3
// Get users that will be added to the users relation.
4
const usersOp = role.op('users');
5
if (usersOp && usersOp.relationsToAdd.length > 0) {
6
// add the users being added to the request context
7
request.context = { buyers: usersOp.relationsToAdd };
8
}
9
};
10
11
const afterSave = function afterSave(request) {
12
const { object: role, context } = request;
13
if (context && context.buyers) {
14
const purchasedItem = getItemFromRole(role);
15
const promises = context.buyers.map(emailBuyer.bind(null, purchasedItem));
16
item.increment('orderCount', context.buyers.length);
17
promises.push(item.save(null, { useMasterKey: true }));
18
Promise.all(promises).catch(request.log.error.bind(request.log));
19
}
20
};
21
Copied!

Delete Triggers

beforeDelete

You can run custom cloud code before an object is deleted. You can do this with the beforeDelete method. For instance, this can be used to implement a restricted delete policy that is more sophisticated than what can be expressed through ACLs. For example, suppose you have a photo album app, where many photos are associated with each album, and you want to prevent the user from deleting an album if it still has a photo in it. You can do that by writing a function like this:
1
Moralis.Cloud.beforeDelete("Album", async (request) => {
2
const query = new Moralis.Query("Photo");
3
query.equalTo("album", request.object);
4
const count = await query.count({useMasterKey:true})
5
if (count > 0) {
6
throw "Can't delete album if it still has photos.";
7
}
8
});
Copied!
If the function throws, the Album object will not be deleted, and the client will get an error. Otherwise, the object will be deleted normally.

PREDEFINED CLASSES

If you want to use beforeDelete for a predefined class in the Moralis JavaScript SDK, you should not pass a string for the first argument. Instead, you should pass the class itself, for example:
1
Moralis.Cloud.beforeDelete(Moralis.User, async (request) => {
2
// code here
3
})
Copied!

afterDelete

In some cases, you may want to perform some type of action, such as a push, after an object has been deleted. You can do this by registering a handler with the afterDelete method. For example, suppose that after deleting a blog post, you also want to delete all associated comments. You can do that by writing a function like this:
1
Moralis.Cloud.afterDelete("Post", (request) => {
2
const query = new Moralis.Query("Comment");
3
query.equalTo("post", request.object);
4
query.find()
5
.then(Moralis.Object.destroyAll)
6
.catch((error) => {
7
console.error("Error finding related comments " + error.code + ": " + error.message);
8
});
9
});
Copied!
The afterDelete handler can access the object that was deleted through request.object. This object is fully fetched, but cannot be refetched or resaved.
The client will receive a successful response to the delete request after the handler terminates, regardless of how the afterDelete terminates. For instance, the client will receive a successful response even if the handler throws an exception. Any errors that occurred while running the handler can be found in the cloud code log.

PREDEFINED CLASSES

If you want to use afterDelete for a predefined class in the Moralis JavaScript SDK, you should not pass a string for the first argument. Instead, you should pass the class itself, for example:
1
Moralis.Cloud.afterDelete(Moralis.User, async (request) => {
2
// code here
3
})
Copied!

File Triggers

beforeSaveFile

With the beforeSaveFile method, you can run custom cloud code before any file is saved. Returning a new Moralis.File will save the new file instead of the one sent by the client.

EXAMPLES

1
// Changing the file name
2
Moralis.Cloud.beforeSaveFile(async (request) => {
3
const { file } = request;
4
const fileData = await file.getData();
5
const newFile = new Moralis.File('a-new-file-name.txt', { base64: fileData });
6
return newFile;
7
});
8
9
// Returning an already saved file
10
Moralis.Cloud.beforeSaveFile((request) => {
11
const { user } = request;
12
const avatar = user.get('avatar'); // this is a Moralis.File that is already saved to the user object
13
return avatar;
14
});
15
16
// Saving a different file from uri
17
Moralis.Cloud.beforeSaveFile((request) => {
18
const newFile = new Moralis.File('some-file-name.txt', { uri: 'www.somewhere.com/file.txt' });
19
return newFile;
20
});
Copied!

METADATA AND TAGS

Adding Metadata and Tags to your files allows you to add additional bits of data to the files that are stored within your storage solution (i.e AWS S3). The beforeSaveFile hook is a great place to set the metadata and/or tags on your files.
Note: not all storage adapters support metadata and tags. Check the documentation for the storage adapter you’re using for compatibility.
1
// Adding metadata and tags
2
Moralis.Cloud.beforeSaveFile((request) => {
3
const { file, user } = request;
4
file.addMetadata('createdById', user.id);
5
file.addTag('groupId', user.get('groupId'));
6
});
Copied!

afterSaveFile

The afterSaveFile method is a great way to keep track of all the files stored in your app. For example:
1
Moralis.Cloud.afterSaveFile(async (request) => {
2
const { file, fileSize, user } = request;
3
const fileObject = new Moralis.Object('FileObject');
4
fileObject.set('file', file);
5
fileObject.set('fileSize', fileSize);
6
fileObject.set('createdBy', user);
7
const token = { sessionToken: user.getSessionToken() };
8
await fileObject.save(null, token);
9
});
Copied!

beforeDeleteFile

You can run custom cloud code before any file gets deleted. For example, let's say you want to add logic that only allows files to be deleted by the user who created it. You could use a combination of the afterSaveFile and the beforeDeleteFile methods as follows:
1
Moralis.Cloud.afterSaveFile(async (request) => {
2
const { file, user } = request;
3
const fileObject = new Moralis.Object('FileObject');
4
fileObject.set('fileName', file.name());
5
fileObject.set('createdBy', user);
6
await fileObject.save(null, { useMasterKey: true );
7
});
8
9
Moralis.Cloud.beforeDeleteFile(async (request) => {
10
const { file, user } = request;
11
const query = new Moralis.Query('FileObject');
12
query.equalTo('fileName', file.name());
13
const fileObject = await query.first({ useMasterKey: true });
14
if (fileObject.get('createdBy').id !== user.id) {
15
throw 'You do not have permission to delete this file';
16
}
17
});
Copied!

afterDeleteFile

In the above beforeDeleteFile example, the FileObject collection is used to keep track of saved files in your app. The afterDeleteFile trigger is a good place to clean up these objects once a file has been successfully deleted.
1
Moralis.Cloud.afterDeleteFile(async (request) => {
2
const { file } = request;
3
const query = new Moralis.Query('FileObject');
4
query.equalTo('fileName', file.name());
5
const fileObject = await query.first({ useMasterKey: true });
6
await fileObject.destroy({ useMasterKey: true });
7
});
Copied!

Find Triggers

beforeFind

In some cases, you may want to transform an incoming query, adding an additional limit or increasing the default limit, adding extra includes, or restrict the results to a subset of keys. You can do so with the beforeFind trigger.

EXAMPLES

1
// Properties available
2
Moralis.Cloud.beforeFind('MyObject', (req) => {
3
let query = req.query; // the Moralis.Query
4
let user = req.user; // the user
5
let triggerName = req.triggerName; // beforeFind
6
let isMaster = req.master; // if the query is run with masterKey
7
let isCount = req.count; // if the query is a count operation
8
let logger = req.log; // the logger
9
let installationId = req.installationId; // The installationId
10
});
11
12
// Selecting keys
13
Moralis.Cloud.beforeFind('MyObject', (req) => {
14
let query = req.query; // the Moralis.Query
15
// Force the selection on some keys
16
query.select(['key1', 'key2']);
17
});
18
19
// Asynchronous support
20
Moralis.Cloud.beforeFind('MyObject', (req) => {
21
let query = req.query;
22
return aPromise().then((results) => {
23
// do something with the results
24
query.containedIn('key', results);
25
});
26
});
27
28
// Returning a different query
29
Moralis.Cloud.beforeFind('MyObject', (req) => {
30
let query = req.query;
31
let otherQuery = new Moralis.Query('MyObject');
32
otherQuery.equalTo('key', 'value');
33
return Moralis.Query.or(query, otherQuery);
34
});
35
36
// Rejecting a query
37
Moralis.Cloud.beforeFind('MyObject', (req) => {
38
// throw an error
39
throw new Moralis.Error(101, 'error');
40
41
// rejecting promise
42
return Promise.reject('error');
43
});
44
45
// Setting the read preference for a query
46
Moralis.Cloud.beforeFind('MyObject2', (req) => {
47
req.readPreference = 'SECONDARY_PREFERRED';
48
req.subqueryReadPreference = 'SECONDARY';
49
req.includeReadPreference = 'PRIMARY';
50
});
51
Copied!

PREDEFINED CLASSES

If you want to use beforeFind for a predefined class in the Moralis JavaScript SDK, you should not pass a string for the first argument. Instead, you should pass the class itself, for example:
1
Moralis.Cloud.beforeFind(Moralis.User, async (request) => {
2
// code here
3
})
Copied!

afterFind

In some cases, you may want to manipulate the results of a query before they are sent to the client. You can do so with the afterFind trigger.
1
Moralis.Cloud.afterFind('MyCustomClass', async (request) => {
2
// code here
3
})
Copied!

PREDEFINED CLASSES

If you want to use afterFind for a predefined class in the Moralis JavaScript SDK, you should not pass a string for the first argument. Instead, you should pass the class itself, for example:
1
Moralis.Cloud.afterFind(Moralis.User, async (request) => {
2
// code here
3
})
Copied!

Session Triggers

beforeLogin

Sometimes you may want to run custom validation on a login request. The beforeLogin trigger can be used for blocking an account from logging in (for example, if they are banned), recording a login event for analytics, notifying a user by email if a login occurred at an unusual IP address and more.
1
Moralis.Cloud.beforeLogin(async request => {
2
const { object: user } = request;
3
if(user.get('isBanned')) {
4
throw new Error('Access denied, you have been banned.')
5
}
6
});
Copied!

SOME CONSIDERATIONS TO BE AWARE OF

  • It waits for any promises to resolve.
  • The user is not available on the request object - the user has not yet been provided a session until after beforeLogin is successfully completed.
  • Like afterSave on Moralis.User, it will not save mutations to the user unless explicitly saved.
THE TRIGGER WILL RUN…
  • On username & password logins.
  • On authProvider logins.
THE TRIGGER WON’T RUN…
  • On sign up.
  • If the login credentials are incorrect.

afterLogout

Sometimes you may want to run actions after a user logs out. For example, the afterLogout trigger can be used for clean-up actions after a user logs out. The triggers contain the session object that has been deleted on logout. From this session object, you can determine the user who logged out to perform user-specific tasks.
1
Moralis.Cloud.afterLogout(async request => {
2
const { object: session } = request;
3
const user = session.get('user');
4
user.set('isOnline', false);
5
user.save(null,{useMasterKey:true});
6
});
Copied!

SOME CONSIDERATIONS TO BE AWARE OF

  • As with with afterDelete triggers, the _Session object that is contained in the request has already been deleted.
THE TRIGGER WILL RUN…
  • When the user logs out and a _Session object was deleted.

THE TRIGGER WON’T RUN…

  • If a user logs out and no _Session object was found to delete.
  • If a _Session object is deleted without the user logging out by calling the logout method of an SDK.

LiveQuery Triggers

beforeConnect

You can run custom cloud code before a user attempts to connect to your LiveQuery server with the beforeConnect method. For instance, this can be used to only allow users that have logged in to connect to the LiveQuery server.
1
Moralis.Cloud.beforeConnect(request => {
2
if (!request.user) {
3
throw "Please login before you attempt to connect."
4
}
5
});
Copied!
In most cases, the connect event is called the first time the client calls subscribe. If this is your use case, you can listen for errors using this event.
1
Moralis.LiveQuery.on('error', (error) => {
2
console.log(error);
3
});
Copied!

beforeSubscribe

In some cases, you may want to transform the incoming subscription query. Examples include adding an additional limit, increasing the default limit, adding extra includes, or restricting the results to a subset of keys. You can do so with the beforeSubscribe trigger.
1
Moralis.Cloud.beforeSubscribe('MyObject', request => {
2
if (!request.user.get('Admin')) {
3
throw new Moralis.Error(101, 'You are not authorized to subscribe to MyObject.');
4
}
5
let query = request.query; // the Moralis.Query
6
query.select("name","year")
7
});
Copied!

afterLiveQueryEvent

In some cases, you may want to manipulate the results of a Live Query before they are sent to the client. You can do so with the afterLiveQueryEvent trigger.

EXAMPLES

1
// Changing values on object and original
2
Moralis.Cloud.afterLiveQueryEvent('MyObject', request => {
3
const object = request.object;
4
object.set('name', '***');
5
6
const original = request.original;
7
original.set('name', 'yolo');
8
});
9
10
// Prevent LiveQuery trigger unless 'foo' is modified
11
Moralis.Cloud.afterLiveQueryEvent('MyObject', (request) => {
12
const object = request.object;
13
const original = request.original;
14
if (!original) {
15
return;
16
}
17
if (object.get('foo') != original.get('foo')) {
18
request.sendEvent = false;
19
}
20
});
Copied!
By default, MoralisLiveQuery does not perform queries that require additional database operations. This is to keep your Moralis Server as fast and efficient as possible. If you require this functionality, you can perform these in afterLiveQueryEvent.
1
// Including an object on LiveQuery event, on update only.
2
Moralis.Cloud.afterLiveQueryEvent('MyObject', async (request) => {
3
if (request.event != "update") {
4
request.sendEvent = false;
5
return;
6
}
7
const object = request.object;
8
const pointer = object.get("child");
9
await pointer.fetch();
10
});
11
12
// Extend matchesQuery functionality to LiveQuery
13
Moralis.Cloud.afterLiveQueryEvent('MyObject', async (request) => {
14
if (request.event != "create") {
15
return;
16
}
17
const query = request.object.relation('children').query();
18
query.equalTo('foo','bart');
19
const first = await query.first();
20
if (!first) {
21
request.sendEvent = false;
22
}
23
});
Copied!

SOME CONSIDERATIONS TO BE AWARE OF

  • Live Query events won’t trigger until the afterLiveQueryEvent trigger has been completed. Make sure any functions inside the trigger are efficient and restrictive to prevent bottlenecks.

onLiveQueryEvent

Sometimes you may want to monitor Live Query Events to be used with a 3rd party such as "Datadog." The onLiveQueryEvent trigger can log events triggered, number of clients connected, number of subscriptions and errors.
1
Moralis.Cloud.onLiveQueryEvent(({
2
event,
3
client,
4
sessionToken,
5
useMasterKey,
6
installationId,
7
clients,
8
subscriptions,
9
error
10
}) => {
11
if (event !== 'ws_disconnect') {
12
return;
13
}
14
// Do your magic
15
});
Copied!

Events

  • connect
  • subscribe
  • unsubscribe
  • ws_connect
  • ws_disconnect
  • ws_disconnect_error
“connect” differs from “ws_connect”, the former means that the client completed the connect procedure as defined by Moralis Live Query protocol, where “ws_connect” just means that a new websocket was created.
Last modified 3mo ago