Caching Management API Access Tokens in Login Action

Problem statement: How do I cache a Management API access token(s) using the Node Management Client and Actions caching functionality?

Auth0 recently announced the ability to cache tokens within our extensibility solution, Actions. This has been a much requested feature that we are excited to have finally released. As many users utilize the Node Management Client to interact with the Management API by way of Actions, the question of how to incorporate the new caching functionality has arisen.

Solution: From within your post-login Action code we recommend adding logic to:

  • Get and/or cache a Management API Access Token if there is not an existing token cached.
  • In order to avoid rate limiting, introduce logic to ensure that the Management API is not called each time a user is logged in.

Example Code

exports.onExecutePostLogin = async (event, api) => {

const ManagementClient = require('auth0').ManagementClient;
const jwt_decode = require('jwt-decode');

//get current value for 'my-api-token'
const record = api.cache.get('my-api-token');
let token = record?.value;
let current_time = / 1000;

if (token != undefined) {
  var decoded = jwt_decode(token);

//Check if cached token exists/is not undefined and not expired
if (token != undefined && decoded.exp > current_time) {
 //Initialize management client with existing token to use against Management API
    const management = new ManagementClient({
      token: token,
      domain: event.secrets.domain,
    //Call Management API
  } else if (token == undefined || decoded.exp < current_time) {
  //Initialize management client with credentials
    const management = new ManagementClient({
    domain: event.secrets.domain,
    clientId: event.secrets.clientID,
    clientSecret: event.secrets.clientSecret,

  //Get new access token and set it in cache
  const newToken = await management.getAccessToken();
    const result = api.cache.set('my-api-token', newToken);
      if (result.type === 'error') {
        console.log("failed to set the token in the cache with error code", result.code)      
      } else {
        console.log("successfully set access token in cache")
  //Initialize management client with new token to use against Management API
  const managementWithToken = new ManagementClient({
      token: newToken,
      domain: event.secrets.domain,
    //Call Management API

:warning: Warning - This is rudimentary example code that needs to be adapted to your own use case, and thoroughly tested.


Related FAQ:

How can I use the Management API in Actions?