# Siren for Medusa: developer guide

This guide is for the developer who installs `@novatorius/siren-medusa`
and wires a store's storefront to it. The store owner's overview is the
package's [README](https://unpkg.com/@novatorius/siren-medusa/README.md).

The plugin connects a Medusa 2 store to Siren Cloud, sends its orders,
refunds, customers, products and promotions there, and gives the
storefront what it needs to credit a referred sale.

## Install and options

The plugin needs Medusa 2.22 or later within Medusa 2 (its Medusa peers are
`^2.22.0`) and Node 20.19 or later.

```sh
npm install @novatorius/siren-medusa
```

Register it in `medusa-config.ts`:

```ts
module.exports = defineConfig({
  // ...
  plugins: [
    {
      resolve: "@novatorius/siren-medusa",
      options: {
        backendUrl: "https://store.example.com",
        encryptionKey: process.env.SIREN_ENCRYPTION_KEY,
      },
    },
  ],
})
```

Then run the plugin's migrations, which add the `siren` module's tables,
and restart Medusa:

```sh
npx medusa db:migrate
```

The plugin checks its options when Medusa loads its `siren` module. A
value it can't use stops Medusa from starting, with a message that names
the option, such as `Siren could not use the backendUrl option: it must use
https, except on localhost.` An option name it doesn't know logs a warning.
No message quotes an option's value.

| Option | Default | Meaning |
| --- | --- | --- |
| `backendUrl` | Medusa's `admin.backendUrl` | The store's address as its admin opens it, such as `https://store.example.com`. One of the two must be an absolute address, or Medusa won't start. |
| `encryptionKey` | a key derived from Medusa's `http.jwtSecret` | 32 random bytes in base64 (`openssl rand -base64 32`). It encrypts the connection's tokens, the signing secret and the customer email key at rest. Set it on a live store: with `NODE_ENV=production`, Siren refuses to start on the derived key when the JWT secret is Medusa's default or shorter than 32 characters, and it warns about the derived key everywhere else. Keep it unchanged once set, since stored secrets only decrypt under the key that wrote them. |
| `publicUrl` | `backendUrl` | Where Siren Cloud delivers the store's webhooks. |
| `adminUrl` | `backendUrl` plus Medusa's `admin.path` (`/app`) | Where the admin dashboard is served. |
| `siteName` | `backendUrl`'s host | What Siren Cloud's consent screen calls the store. |
| `cloudApiUrl`, `cloudAppUrl` | Siren Cloud | Siren Cloud's API and app addresses. Leave them unset on a live store. |
| `httpClient` | the SDK's fetch client | The client every Siren Cloud request goes through. Tests pass a fake. |

The query parameter that carries a referral code belongs to the storefront.
To use one other than `ref`, pass `param` to `captureReferral` and make sure
partner links carry that same name. The plugin has no server option for it,
and a `trackingParam` entry in `medusa-config.ts` only logs a warning that
says so.

Every address option must be absolute and use https. Plain http is
accepted only on `localhost`, `127.0.0.1`, `[::1]`, or a host the
`SIREN_DEV_HTTP_HOSTS` environment setting names exactly, which is meant
for test systems and logs a warning at boot.

Siren Cloud must be able to reach `publicUrl` from the internet. After
the connect, the Siren page in the admin shows whether it can, and the
plugin starts sending orders only once it can.

## The storefront

A Medusa storefront is its own app, so the plugin ships a small entry
for it: `@novatorius/siren-medusa/storefront`. It imports nothing, runs
in a browser, Node or an edge runtime, and never pulls the plugin's
server code into the storefront's bundle.

A referred sale takes two calls:

1. When a shopper arrives with a referral code in the URL (`?ref=alice` by
   default), `captureReferral` records the visit with the store, which
   asks Siren Cloud, and keeps the token Siren Cloud answers in the
   `siren_tracking` cookie for 30 days.
2. When the storefront makes the shopper's cart, `attachTrackingToCart`
   writes that token on the cart's metadata. Medusa copies the cart's
   metadata onto the order, and the plugin reads it from there when the
   order is placed.

### `captureReferral(options): Promise<string | null>`

| Option | Type | Meaning |
| --- | --- | --- |
| `sdk` | `@medusajs/js-sdk` client | Sends the publishable key, which Medusa requires on every `/store` route. |
| `url` | `string \| URL` | The page's address, which may carry the code. |
| `cookies` | `SirenCookies` | Reads and sets a cookie by name. Next.js's cookie stores fit as they are. |
| `param` | `string`, default `ref` | The query parameter that carries the code. |
| `secure` | `boolean`, default whether `url` is https | Whether the cookie is sent over https only. |
| `logger` | `{ warning(message), debug?(message) }`, default `console.warn` and `console.debug` | Where a failed call is reported, and a dropped bare id is noted at debug. A TS Nomad `LoggerStrategy` fits. |

It answers the shopper's token: the new one when Siren Cloud sent one,
else the one the cookie already held, else null. It sends nothing when
the URL has no code or a code over 191 bytes. It gives up after three
seconds and never rejects, so a lost visit costs a page three seconds at
most. No message it logs carries a code or a token.

### `attachTrackingToCart(options): Promise<boolean>`

| Option | Type | Meaning |
| --- | --- | --- |
| `sdk` | `@medusajs/js-sdk` client | As above. |
| `cartId` | `string` | The shopper's cart. |
| `token` | `string \| null \| undefined` | The token, from `readTrackingToken` or `captureReferral`. |
| `logger` | `{ warning(message), debug?(message) }` | As above. |

It answers true when it sent the write. Medusa merges metadata keys, so
the cart keeps any other metadata the storefront set. With no usable
token it sends nothing and answers false. An empty cart id or a failed
write answers false with a warning.

### `readTrackingToken(cookies, logger?): string | null`

The token in the `siren_tracking` cookie, or null when there is none or
it is not a Siren token.

A Siren token is signed: the opportunity number, a period and Siren
Cloud's signature, as `TOKEN_PATTERN` and `isTrackingToken` check. A bare
opportunity number, such as `318`, is no token. Every helper drops one
with a debug line that does not quote it, and never sends it, keeps it in
the cookie or writes it on the cart, since Siren Cloud would credit
whichever partner owns any number a shopper typed.

### Constants

`TRACKING_COOKIE` (`siren_tracking`), `TRACKING_METADATA_KEY`
(`siren_tracking_token`), `DEFAULT_TRACKING_PARAM` (`ref`),
`ATTRIBUTION_WINDOW_SECONDS` (30 days), `VISIT_TIMEOUT_MS` (3000) and
`TOKEN_PATTERN`, with `isTrackingToken(value)` and
`isBareOpportunityId(value)`, the rule the plugin's own readers use.

### In the Next.js starter storefront

Medusa's Next.js starter is the storefront in `apps/storefront` of
[medusajs/dtc-starter](https://github.com/medusajs/dtc-starter), which
`create-medusa-app` sets up. These steps are proven against its commit
`6440e85` (Medusa 2.22.6, Next.js 16.3) by this repository's
`uat/medusa/next-starter/`.

Record the visit in `src/middleware.ts`, which runs before every page in
Next.js's edge runtime. The helpers and the starter's `sdk` both run there.
Put the call in the branch that serves the page, before it returns
`response`. A link without the country code, such as `/products/mug?ref=pat`,
is redirected to `/<country>/products/mug?ref=pat` with the code kept, so the
visit is recorded once, on the redirected request.

```ts
import { captureReferral } from "@novatorius/siren-medusa/storefront"
import { sdk } from "@lib/config"

// In middleware(), inside `if (urlHasCountry || request.nextUrl.pathname === "/")`,
// after the starter builds `response`:
// Only a page load records the visit. The starter's router fetches and
// server actions carry the page's URL, and its `ref`, too.
const isPageLoad =
  request.method === "GET" &&
  request.headers.get("sec-fetch-dest") !== "empty"
if (isPageLoad && request.nextUrl.searchParams.has("ref")) {
  await captureReferral({
    sdk,
    url: request.nextUrl,
    cookies: {
      get: (name) => request.cookies.get(name),
      set: (name, value, options) => response.cookies.set(name, value, options),
    },
  })
}
return response
```

Without the page-load check, the starter records the visit again on every
router fetch and server action from a page whose URL still holds `?ref=`,
such as each "Add to cart", and each of those waits on Siren Cloud.

Write the token on the cart in two places, so every cart the shopper ends
up with carries it.

In `src/lib/data/cart.ts`, at the end of `getOrSetCart`, just before
`return cart`. The starter's "Add to cart" button calls it for every item,
so a cart made before the shopper's referral landing takes the token with
the next item:

```ts
import { attachTrackingToCart, readTrackingToken } from "@novatorius/siren-medusa/storefront"
import { cookies } from "next/headers"

await attachTrackingToCart({
  sdk,
  cartId: cart.id,
  token: readTrackingToken(await cookies()),
})

return cart
```

In `src/lib/util/server-cart.ts`, in `activateCart`, right after
`setCartId(cartId)`. That covers the carts the starter makes outside
`getOrSetCart`: the add-to-cart form without JavaScript (`/<country>/cart/add`),
buy links (`/buy/<variant>:<quantity>`) and a cart an agent built through
the starter's `/ucp` routes when the shopper opens it:

```ts
import { attachTrackingToCart, readTrackingToken } from "@novatorius/siren-medusa/storefront"
import { cookies } from "next/headers"

export const activateCart = async (cartId: string) => {
  await setCartId(cartId)
  await attachTrackingToCart({
    sdk,
    cartId,
    token: readTrackingToken(await cookies()),
  })
  // ...the starter's cache revalidation
}
```

With no token in the cookie, `attachTrackingToCart` sends nothing, so a
shopper who came with no referral costs no extra call. A referred shopper
costs one cart update per item added.

The starter's middleware skips `/api`, `/ucp` and `/buy`, so a referral code
on a buy link itself is not recorded. Send partners' links to a page.

## Events from Siren Cloud

Each event Siren Cloud sends the store reaches Medusa's event bus as
`siren.<type>`, such as `siren.conversion.approved`, with the event's
fields as its data. A Medusa subscriber listens for it as for any other
event:

```ts
export const config = { event: "siren.conversion.approved" }
```

Write a subscriber so that it can run twice for one event, and so that
it can miss one. Siren Cloud may deliver an event again, and the plugin
passes each delivery on once without retrying a failed emit. Use the
event's own fields, such as a conversion's id, to tell a repeat from a
new event.

## Scheduled jobs

| Job | When | What |
| --- | --- | --- |
| `siren-every-minute` | every minute | sends the outbox's due retries and delayed tasks, and reads the Siren Cloud plan when it is due |
| `siren-held-tasks` | every minute | runs again each held event whose wait has passed with no handler clearing it |
| `siren-sync-promotions` | every five minutes | sends changed promotions as coupons, starts the coupon import after the store connects and weekly, and resumes any coupon import or product catalog sync a restart interrupted |
| `siren-reconcile-refunds` | daily at 03:29 | sends any refund of the last three days that Siren Cloud has not had |
| `siren-daily` | daily at 03:17 | reports the store's state and integrations to Siren Cloud, resumes open jobs and prunes old rows |
