# Shipping

Declare where you ship and what it costs. No code, just rules per country.

Shipping lives in the Channel. The countries you list are the countries you ship
to. Every other country gets `ship_to_unsupported`.

```ts title="src/worker.ts" members="ChannelConfig"
shipping: {
  DE: [
    { id: "standard", title: "Standard (DHL)", price: 495, deliveryTime: "2-4 business days" },
    { id: "express", title: "Express", price: 1290, deliveryTime: "1 business day" },
  ],
  AT: [{ id: "standard", title: "Standard", price: 790, deliveryTime: "3-5 business days" }],
},
```

Prices are in minor units of the Channel's currency. `495` is €4.95.

## Rule options

| Option         | Required | Example               | What it does                                                          |
| -------------- | -------- | --------------------- | --------------------------------------------------------------------- |
| `id`           | yes      | `"express"`           | Your ID. Unique per country.                                          |
| `title`        | yes      | `"Express"`           | What the buyer sees.                                                  |
| `price`        | yes      | `1290`                | Minor units. `0` for free shipping. Or tiers by weight, see below.    |
| `deliveryTime` |          | `"1 business day"`    | Your text. Shown as is, never calculated.                             |
| `requires`     |          | `["phone"]`           | Contact fields this method needs, such as a phone number for freight. |
| `excludes`     |          | `["lithium_battery"]` | Offer restrictions this method cannot carry.                          |
| `only`         |          | `["bulky"]`           | Offered only when a Line carries one of these restrictions.           |

## Which method is selected?

The buyer's choice. Until they choose, the cheapest method. The Cart shows what's
on offer right now:

```ts browser
current.shippingMethods; // [{ id: "standard", ... }, { id: "express", ... }]
current.shipping; // { id: "standard" }

await cart.setShipping("express");
```

## Keep goods off a method

Mark goods in your `offers` function:

```ts members="OfferedReference"
shipping: { weightInGrams: 180, restrictions: ["lithium_battery"] },
```

Then exclude the restriction on the rule that cannot carry it:

```ts items="ShippingRuleConfig"
{ id: "express", title: "Express", price: 1290, excludes: ["lithium_battery"] },
```

Express disappears for that Cart. `cart.changes` explains why with a
`shipping_unavailable` entry, so you can tell the buyer. If no method is left for
a country, the Quote fails with `not_shippable` and `problem.lines` names the
Lines to remove.

## Price by weight

Give `price` as tiers, lightest first:

```ts items="ShippingRuleConfig"
{
  id: "standard",
  title: "Standard (DHL)",
  price: [
    { upToGrams: 2000, price: 495 },
    { upToGrams: 10000, price: 695 },
    { price: 995 }, // any weight above
  ],
},
{ id: "express", title: "Express", price: [{ upToGrams: 10000, price: 1290 }] },
```

* **The weight** is every shipped unit together, from `weightInGrams` in your Offers.
* **The first tier that fits** sets the price.
* **A last tier without `upToGrams`** covers any weight. With a limit, like express above, the method
  disappears for heavier Carts and `cart.changes` says why (`reason: "too_heavy"`). Keep one method open
  for any weight, so a large order always ships.
* **An Offer without `weightInGrams`** counts as 0 g. Your logs name it as `weight_missing`.

## Bulky goods by freight

Mark the goods with a restriction such as `bulky`, keep it off the parcel methods with `excludes`, and offer
freight with `only`:

```ts items="ShippingRuleConfig"
{ id: "standard", title: "Standard (DHL)", price: 495, excludes: ["bulky"] },
{ id: "freight", title: "Freight", price: 4900, requires: ["phone"], only: ["bulky"] },
```

A Cart with a canoe gets freight alone. A pair of socks never sees it. Put `bulky` in `excludes` on every
parcel method, or the cheaper parcel is preselected for the canoe.

## Goods that take longer

A rule's `deliveryTime` is the parcel's time. Goods that ship later, such as an engraving, say so with their own
`deliveryTime` in your `offers` function. The buyer sees both: the Line's time on the Line, the method's beside
the method. See [Offers](/integrations#say-when-goods-take-longer).

## Digital goods

Leave out `shipping` in the Offer. A Cart with only digital goods needs no
delivery address and no shipping method.

## Many countries, one price

A small helper keeps long lists readable. This is how Nordgrat ships to price zones
across the EU:

```ts
function zone(countries: string[], price: number, deliveryTime: string) {
  const standard = { id: "standard", title: "Standard (DHL)", price, deliveryTime };
  return Object.fromEntries(countries.map((country) => [country, [standard]]));
}
```

The channel then lists its own countries and spreads the zones:

```ts continues members="ChannelConfig"
shipping: {
  DE: [standard, express],
  ...zone(["BE", "NL", "LU", "DK"], 890, "3-5 business days"),
  ...zone(["FR", "IT", "ES", "SE"], 990, "4-6 business days"),
},
```

## Free shipping from €50

Use a [discount](/commerce/discounts) with `scope: "shipping"`. Name the methods it frees in `methods`,
so express stays paid:

```ts members="ChannelConfig"
discounts: [
  { id: "free-shipping", scope: "shipping", percentage: 100, minimumSubtotal: 5000, methods: ["standard"] },
],
```

Without a `code`, it applies automatically.

## DHL Packstation and pickup points

`@orbcart/plugin-dhl` adds a pickup finder to the React checkout, for Germany.
The buyer picks a Packstation or post office on a map, and it becomes the
delivery address:

```tsx browser
import { DhlDeliveryAddress, DhlPickupProvider } from "@orbcart/plugin-dhl/react";
import "@orbcart/plugin-dhl/styles.css";

<DhlPickupProvider enabled countries={["DE"]} searchUrl="/pickup/locations" locale="de-DE">
  <Checkout cart={cart} locale="de-DE" deliveryAddress={DhlDeliveryAddress} />
</DhlPickupProvider>;
```

Each Packstation shows a green, yellow or red dot for how much space it usually has.
The search runs on your server, at the `searchUrl` you name, with your DHL API key:

```ts title="app/routes/pickup.locations.ts"
import { env } from "cloudflare:workers";
import { PickupSearch } from "@orbcart/plugin-dhl";
import { findDhlLocations } from "@orbcart/plugin-dhl/server";

export async function action({ request }: { request: Request }) {
  // Only your own checkout may spend your DHL quota.
  if (request.headers.get("Origin") !== new URL(request.url).origin) {
    return new Response(null, { status: 403 });
  }
  const search = PickupSearch.safeParse(await request.json());
  if (!search.success) return Response.json({ error: "invalid_query" }, { status: 400 });

  const result = await findDhlLocations({
    apiKey: env.DHL_API_KEY,
    search: search.data,
    signal: request.signal,
  });
  const headers = { "Cache-Control": "private, no-store" };
  return result.status === "success"
    ? Response.json({ locations: result.locations }, { headers })
    : Response.json({ error: result.error }, { status: 503, headers });
}
```

Use DHL's API Key, not the API Secret, with a Location Finder Unified subscription. Keep
`@orbcart/plugin-dhl/server` out of browser code. `packages/plugin-dhl/README.md` lists the error
codes and what the finder does not promise yet. [How a plugin is shaped →](/extend#package-it-for-other-shops)

[Set up discounts →](/commerce/discounts)