Events

Clerkjs: Events

When building more customised setups, such as for B2B businesses, you will often need to react to or modify the results from Clerk before rendering them.

This is where Events are useful.

Events allow you to set up event listeners that run code at specific times before, during, or after Clerk.js renders its results. A common use-case is when you need to check which user is logged in and fetch specific prices for their customer group or remove products they are not allowed to see.

For example, an event can run immediately after Clerk’s API responds, allowing you to call your pricing database with the ID of the customer and the products returned by Clerk to fetch the correct prices before Clerk.js renders the results.

Clerk("on", "response", function(content, data) {
    let products = data['product_data'];
    const product_ids = data['result'];
    const customer_prices = getUniquePrices(customer_group, product_ids); // {"27746": 310.25, "26994": 124.50}
    products.forEach(product =>
      product['price'] = customer_prices[product['id']]) // Add customer price based on product ID;
  })