How do I call my API from a rule?

Question: How do I call my API from a rule?


To do this, you will need to configure your rule to make an API call. You can add Machine 2 Machine (M2M) authorization between your the rule and the your target API, just like you would between any two non-interactive clients, protecting the transaction with Auth0.

First, register your API.

This can be done via the Dashboard or the Management API. In the Dashboard, navigate to APIs -> + Create API. Here you can set up your API, register your permissions, and manage your M2M applications.

Next, register an application for your rule.

Navigate to Applications -> + Create Application. Here you will select a M2M application, and link it to the API you just created.

Finally, we need to create the rule.

Navigate to Rules -> + Create Rule -> </> Empty Rule. Here we can request an access token designated for the API we registered, and then make whatever API call we need. After we create the rule, add your client ID and client secret to the global configuration object in the settings section.

Here is an example:

function (user, context, callback) {
  const axios = require('axios@0.19.2');

  //Request the access token
  const options = { method: 'POST',
    url: `https://${auth0.domain}/oauth/token`,
    headers: { 'content-type': 'application/json' },
    data: `{"client_id":"${configuration.RULE_APP_CLIENT_ID}","client_secret":"${configuration.RULE_APP_CLIENT_SECRET}","audience":"https://test-api","grant_type":"client_credentials"}` };

    .then( res => {
      const access_token =;
    	//Call your API
    .catch( err => {
  return callback(null, user, context);

Note: We are using axios 0.19.2, the latest version available in rules. Make sure to check what Node.js modules are available in rules.

Rules are powerful.

Rules run after every successful authentication. This is something to keep in mind when deciding how to sequence your rules, and whether you should do this on every authentication or conditionally. Long API calls will make authenticating take more time. It is recommended that more expensive rules (like an API call), are run last. For example, if you are going to return an unauthorized error if the user hasn’t verified their email, do that before calling your API.

Good luck! Let us know if you have any questions.

Supporting Documentation:


1 Like