A remote hook is a function that's executed before or after a remote method.

Page Contents

Get the app (in the state following the last article) from GitHub and install all its dependencies:

$ git clone https://github.com/strongloop/loopback-getting-started-intermediate.git
$ cd loopback-getting-started-intermediate
$ git checkout step4
$ npm install

Introducing remote hooks

A remote hook is simply a function that gets executed before or after a remote method (either a custom remote method or a built-in CRUD method).   In this example, you’re going to define a remote hook that is called whenever the create() method is called on the Review model; that is, when a new review is created.

You can define two kinds of remote hooks:

  • beforeRemote() runs before the remote method.
  • afterRemote() runs after the remote method.

In both cases, you provide two arguments: a string that matches the remote method to which you want to “hook” your function, and a callback function.  Much of the power of remote hooks is that the string can include wildcards, so it is triggered by any matching method.

Create the remote hook

Here, you’re going to define a remote hook on the review model, specifically Review.beforeRemote.

Modify common/models/review.js, and add the following code:


module.exports = function(Review) {
  Review.beforeRemote('create', function(context, user, next) {
    context.args.data.date = Date.now();
    context.args.data.publisherId = context.req.accessToken.userId;

This function is called before a new instance of the Review model is created.  The code:

  • Inserts the publisherId using the access token attached to the request.
  • Sets the date of the review instance to the current date.

Next: Continue to Create AngularJS client.