Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 33 ยท Projects

Project: A Loyalty Points Program

Build loyalty points in Medusa 2: a points module with a ledger, an order-placed subscriber, a workflow with compensation, checkout redemption and a balance route.

A loyalty program rewards repeat customers: spend money, earn points, spend points on a discount. It looks simple, but it is a small financial system, and the same bugs appear every time: points awarded twice because an event was delivered twice, points spent that were never earned, balances that drift because a failure left a half-written change. Medusa's building blocks (modules, subscribers, workflows with compensation and hooks) are exactly the tools that prevent them.

In this project you design the points ledger, award points from an order-placed subscriber through a workflow, let customers redeem points at checkout through a hook, and expose a balance route. The Medusa code is read-only; two runnable stand-ins implement the ledger and the checkout rules so you can test the edge cases.

The rules

  1. Customers earn 1 point per whole currency unit of the order total (a 45.99 order earns 45 points).
  2. 100 points are worth 1.00 of discount when redeemed.
  3. A redemption can cover at most 50% of the cart subtotal, and never more than the balance.
  4. Points are awarded once per order, even if the event is delivered again.
  5. If anything fails while placing the order, redeemed points are returned.

Why a ledger, not a balance column

Storing one balance number that you add to and subtract from is fragile: two concurrent updates can overwrite each other, and you cannot explain how the number came to be. An append-only ledger records every change as a row; the balance is the sum. Corrections are new rows, never edits. This mirrors how accounting works and is covered for money in Money as integers.

flowchart LR
    O["order.placed event"] --> SUB["Subscriber"]
    SUB --> W["earnPointsWorkflow"]
    W --> L[("points ledger<br/>append-only rows")]
    C["Checkout: complete cart"] --> H["Hook: validate redemption"]
    H --> L
    API["GET /store/customers/me/loyalty"] --> L

Every change is a ledger row; the balance route, the subscriber and the checkout hook all read or append to it.

Step 1: the module

A custom module with one model (Custom Modules and Data Models). Read-only code:

TypeScript
// src/modules/loyalty/models/points-entry.ts
import { model } from "@medusajs/framework/utils"

export const PointsEntry = model
  .define("points_entry", {
    id: model.id().primaryKey(),
    customer_id: model.text().index(),
    delta: model.number(), // positive = earned, negative = spent
    reason: model.enum(["earned", "redeemed", "refunded", "adjustment"]),
    order_id: model.text().nullable(),
  })
  .indexes([
    {
      on: ["order_id", "reason"],
      unique: true,
      where: "order_id IS NOT NULL",
    },
  ])

The partial unique index is the safety net behind rule 4: the database itself refuses a second earned row for the same order. Business code should still check first, so users and logs see a clean outcome instead of a constraint error. Confirm the exact indexes options for your Medusa version in the docs.

TypeScript
// src/modules/loyalty/service.ts
import { MedusaService } from "@medusajs/framework/utils"
import { PointsEntry } from "./models/points-entry"

class LoyaltyModuleService extends MedusaService({ PointsEntry }) {
  async getBalance(customerId: string): Promise<number> {
    const entries = await this.listPointsEntries({ customer_id: customerId })
    return entries.reduce((sum, entry) => sum + entry.delta, 0)
  }
}

export default LoyaltyModuleService

For a very large ledger you would keep a running total or use a database SUM, but summing is correct and simple to start with. Register the module in medusa-config.ts, then run npx medusa db:generate loyalty and npx medusa db:migrate.

Step 2: earning points with a workflow

The earn workflow has two steps: skip if this order was already rewarded, then append the ledger row. The second step has a compensation so that if a later step (say, sending a congratulations email) fails, the points are removed again (Compensation, Rollback and Long-Running Workflows).

TypeScript
// src/workflows/earn-points.ts
import {
  createStep,
  createWorkflow,
  StepResponse,
  WorkflowResponse,
  transform,
} from "@medusajs/framework/workflows-sdk"
import { LOYALTY_MODULE } from "../modules/loyalty"

type Input = { order_id: string; customer_id: string; total: number }

const calculatePointsStep = createStep("calculate-points", async (input: Input) => {
  const points = Math.floor(input.total / 100) // total is in minor units
  return new StepResponse(points)
})

const appendEarnedStep = createStep(
  "append-earned-points",
  async (input: { order_id: string; customer_id: string; points: number }, { container }) => {
    const loyalty = container.resolve(LOYALTY_MODULE)
    const already = await loyalty.listPointsEntries({
      order_id: input.order_id,
      reason: "earned",
    })
    if (already.length > 0 || input.points <= 0) {
      return new StepResponse(null) // nothing to undo
    }
    const entry = await loyalty.createPointsEntries({
      customer_id: input.customer_id,
      delta: input.points,
      reason: "earned",
      order_id: input.order_id,
    })
    return new StepResponse(entry, entry.id)
  },
  async (entryId, { container }) => {
    if (!entryId) return
    await container.resolve(LOYALTY_MODULE).deletePointsEntries(entryId)
  }
)

export const earnPointsWorkflow = createWorkflow("earn-points", (input: Input) => {
  const points = calculatePointsStep(input)
  const entry = appendEarnedStep(
    transform({ input, points }, (d) => ({ ...d.input, points: d.points }))
  )
  return new WorkflowResponse(entry)
})

Note the order total is an integer in minor units (cents), so Math.floor(total / 100) is exact integer math, no floating point.

Step 3: the order-placed subscriber

Events are delivered at least once, so the handler must be safe to run twice; the duplicate check above does exactly that (Events and Subscribers).

TypeScript
// src/subscribers/order-placed-loyalty.ts
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
import { earnPointsWorkflow } from "../workflows/earn-points"

export default async function orderPlacedLoyalty({
  event: { data },
  container,
}: SubscriberArgs<{ id: string }>) {
  const query = container.resolve("query")
  const { data: orders } = await query.graph({
    entity: "order",
    fields: ["id", "customer_id", "total"],
    filters: { id: data.id },
  })
  const order = orders[0]
  if (!order?.customer_id) return // guest checkout earns nothing

  await earnPointsWorkflow(container).run({
    input: { order_id: order.id, customer_id: order.customer_id, total: Number(order.total) },
  })
}

export const config: SubscriberConfig = { event: "order.placed" }

Step 4: redeeming at checkout

The storefront stores the requested points in the cart metadata (for example points_to_redeem). The discount itself is a price rule you create, for instance by adding a negative adjustment or a generated single-use promotion; the loyalty-specific job is validation. Core workflows such as completeCartWorkflow expose hooks where your code can run and reject the operation (Hooks and Built-in Workflows). A sketch (hook names and payloads differ between releases, so check the workflow reference for your version):

TypeScript
// src/workflows/hooks/complete-cart.ts
import { completeCartWorkflow } from "@medusajs/medusa/core-flows"
import { MedusaError } from "@medusajs/framework/utils"
import { LOYALTY_MODULE } from "../../modules/loyalty"

completeCartWorkflow.hooks.validate(async ({ cart }, { container }) => {
  const requested = Number(cart.metadata?.points_to_redeem ?? 0)
  if (!requested) return

  const loyalty = container.resolve(LOYALTY_MODULE)
  const balance = await loyalty.getBalance(cart.customer_id)
  // 100 points = 1.00, so 1 point = 1 minor unit (one cent)
  const cap = Math.floor(Number(cart.subtotal) / 2) // 50% of the subtotal

  if (requested > balance || requested > cap) {
    throw new MedusaError(
      MedusaError.Types.NOT_ALLOWED,
      "Not enough points, or more than 50% of the cart"
    )
  }
})

The same rules run again when the redemption is recorded, because a validate hook only checks; a second hook or the order-placed flow appends the redeemed row (a negative delta tied to the order). Always re-check at write time, since the balance can change between validation and completion. This is the same reasoning as inventory reservations (Inventory reservations).

Step 5: the balance route

TypeScript
// src/api/store/customers/me/loyalty/route.ts
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { LOYALTY_MODULE } from "../../../../../modules/loyalty"

export async function GET(req: MedusaRequest, res: MedusaResponse) {
  const loyalty = req.scope.resolve(LOYALTY_MODULE)
  const customerId = req.auth_context.actor_id
  const entries = await loyalty.listPointsEntries(
    { customer_id: customerId },
    { order: { created_at: "DESC" }, take: 20 }
  )
  const balance = await loyalty.getBalance(customerId)
  res.json({ balance, entries })
}

The middleware marks it as customer-authenticated, so one customer can never read another's ledger.

Stand-in 1: the ledger

Earning is idempotent per order, and redemption refuses to overspend. Run it and read the balance after each action.

JS An append-only points ledger

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The duplicate delivery adds nothing, and the oversized redemption leaves the balance untouched.

Stand-in 2: checkout with rollback

Here the checkout flow validates the redemption against the 50% cap, reserves the points as a ledger row, then continues with a later step that can fail (a payment). If it fails, the redemption row is removed, which is the compensation.

JS Redeem at checkout, roll back on failure

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check the numbers: the first order may use up to 2000 points but only 500 were requested, so the balance drops from 600 to 100. The declined payment is rolled back, and the last order fits the remaining 100 exactly.

Hardening ideas

  • Expire points after a period by appending adjustment rows from a scheduled job (Scheduled Jobs).
  • Return points when an order is canceled or refunded (refunded rows), keyed by the order id so it also stays idempotent.
  • Cap daily earning per customer and watch for abuse patterns (Fraud prevention).
  • Test the double-delivery and rollback cases first (Testing Modules, Workflows and APIs).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why use an append-only ledger instead of a single balance column?

    A ledger explains how a balance came to be and avoids lost updates. The balance is derived by summing signed entries.
  2. 2. The order.placed event is delivered twice. How does the earn workflow avoid awarding points twice?

    Events are at-least-once, so the handler must be idempotent. Checking for an earned row per order is the application rule; the unique index is the safety net.
  3. 3. Why is order total handled with Math.floor(total / 100)?

    Money is stored as integers in minor units such as cents. Dividing by 100 and flooring gives exact whole units.
  4. 4. What should happen to redeemed points if payment fails during checkout?

    Compensation undoes completed steps when a later step fails, so the customer never loses points for an order that did not happen.
  5. 5. Why re-check the balance when recording a redemption even though a validate hook already checked it?

    Another order or an expiry job may change the balance after validation. Checking again at write time closes that gap.

Summary

  • Model points as an append-only ledger with signed delta rows; the balance is their sum.
  • Award points from an order.placed subscriber through a workflow whose steps are idempotent and have compensation.
  • Validate redemptions at checkout with a workflow hook, enforce the cap and balance, and re-check when writing.
  • Keep money and points as integers, and expose a customer-authenticated balance route.
  • The stand-ins reproduce the rules; the Medusa code is read-only and hook names should be checked for your version.

Next: Project: Syncing Products with an External System