Cloudhooks Help

Hook context

When building e-commerce integrations, your hooks often need to behave differently during testing or know which store is executing them. Hook context provides this environmental awareness to your hooks.

What is hook context?

Hook context is a parameter of the hook function that provides information about the hook's environment: test mode status, store details, environment variables and OAuth access tokens.

Available properties

env: objectValues of the environment variables available to the hook, by variable name: context.env.<name>
oauth: objectAccess tokens of the OAuth connections available to the hook, by connection name: context.oauth.<name>.accessToken
isTestMode: booleanDetermines whether the hook is run in test mode
shopifyDomain: stringThe domain of the store

Common use cases

Here's how to use hook context to create smarter hooks:

module.exports = async function (payload, actions, context) {
  // Use different API endpoints based on test/production mode
  const api = context.isTestMode ? 
    'https://dev.myapi.com' : 
    'https://myapi.com';
 
  // Include store information in API calls
  const { data } = await actions.http.post(api, {
    store: context.shopifyDomain,
    payload: payload
  });
}

Calling APIs with credentials

env and oauth keep credentials out of your hook code:

  • Use env for static values, such as API keys, base URLs and other configuration.
  • Use oauth for APIs that require an OAuth access token. Each OAuth connection available to the hook has an entry with accessToken, tokenType and expiresAt. Cloudhooks fetches and renews the token for you. accessToken is null when no token is available, so check it before you use it. Cloudhooks logs the reason in the run log: if the token couldn't be fetched, as an error that marks the run as failed. Only a missing connection, for example a mistyped name, isn't logged, so log it yourself.
module.exports = async function (payload, actions, context) {
  const crm = context.oauth.crm;
  if (!crm) {
    // No connection named "crm" is available to this hook: nothing else logs this.
    console.error('No "crm" OAuth connection is available to this hook.');
    return;
  }
  const token = crm.accessToken;
  // No token: Cloudhooks has already logged the reason in the run log.
  if (!token) return;
 
  await actions.http.post(`${context.env.CRM_API_URL}/customers`, payload, {
    headers: { Authorization: `Bearer ${token}` }
  });
}

Best Practices

  • Check isTestMode when making external API calls
  • Use shopifyDomain for logging and tracking store-specific issues
  • Check oauth entries for a null access token before calling the API