Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 109 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,111 @@
# sfcc-commerce

[Next.js Commerce for Salesforce Commerce Cloud](https://github.com/vercel-partner-solutions/nextjs-salesforce-commerce-cloud) on
**Cloudflare Workers**, deployed by [Orun](https://github.com/sourceplane/orun) to stage
and prod on every merge, and then packaged as an Orun baseline.

This commit is the repository's frame: `intent.yaml` (with the placeholder
workspace `ws_CHANGE_ME`, so CI plans nothing until it is linked), the Orun
CI workflow, the shared TypeScript and ESLint configuration, and the spec
index. The work is tracked as an epic under [`specs/epics`](specs/epics/README.md).
Vercel's [Next.js Commerce for Salesforce Commerce Cloud](https://github.com/vercel-partner-solutions/nextjs-salesforce-commerce-cloud)
— Next.js Commerce on Salesforce B2C Commerce's Shopper APIs (SCAPI): a home
page with a featured grid and a carousel, the catalogue's categories with
sorting, search, product pages with variants and recommendations, a cart and
a guest checkout, every shopper a SLAS guest and every catalogue read a
`"use cache"` entry dropped by tag when the catalogue changes — running on
**Cloudflare Workers + Static Assets** through
[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), with the
Next.js data cache in an **R2 bucket** provisioned by Terraform through
[Orun](https://github.com/sourceplane/orun) and the tag cache and revalidation
queue in **Durable Objects** the Worker itself exports, deployed by
[Orun](https://github.com/sourceplane/orun) to stage and prod on every merge.
Packaging it as an Orun baseline is the next milestone (SX2).

A fresh build needs no Salesforce store: until its owner connects one, `/`
says "Connect your Salesforce Commerce Cloud store" and every other page
answers with an empty catalogue and the same note — never a 500. The owner
connects a store by setting its SLAS client id, organization, short code and
site as Orun secrets (and a private client's secret) and redeploying. The
Worker is about 2.5 MiB gzipped (`next build --webpack`), inside Workers
Free's 3 MiB. See [`specs/epics/sfcc-commerce`](specs/epics/sfcc-commerce/README.md)
for the design, the milestones and the as-built status.

## What is here (the product)

| Surface | Where |
|---|---|
| The storefront's routes: `/`, `/search`, `/search/<category>`, `/product/<id>`, the content pages, `/checkout`, `/api/revalidate`, `/api/health`, the sitemap and the Open Graph images | `apps/web/app` |
| The store's name and its source link | `apps/web/app/site.ts` (`SITE_NAME`, `SOURCE_URL`) |
| Whether a Salesforce store is connected, and what the storefront says until one is | `apps/web/lib/sfcc/connection.ts`, `apps/web/components/connect-store.tsx` |
| The SCAPI client, the SLAS guest login, the cached reads and their tags, the cart and checkout, the revalidation route's logic | `apps/web/lib/sfcc` |
| Workers build, cache bindings and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.template.jsonc` + `wiring.fixture.json` (→ the committed `wrangler.jsonc`), `component.yaml` |
| The R2 bucket (stage, prod) | `infra/terraform/cloudflare-r2` |
| The wrangler renderer, and the step that puts `SFCC_SECRET` and the revalidation secret on the Worker | `tooling/wire` |
| Tests | `tests/web` (the port's seams: the store name, the connection and its guest logins, health, the URL helpers, revalidation) |

## Getting started

```bash
pnpm install
pnpm run wire:fixture # render apps/web/wrangler.jsonc from the offline fixture
pnpm typecheck
pnpm lint
pnpm test
pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next
```

```bash
pnpm --filter @app/web dev # http://localhost:3000, Next's dev server
pnpm --filter @app/web preview # wrangler dev over the built Worker, a local R2 bucket and local Durable Objects
```

With no `SFCC_*` coordinates both serve the "connect your Salesforce Commerce
Cloud store" storefront. To run against a store, put its four coordinates in
`apps/web/.env.local` (from `apps/web/.env.example`, which lists Salesforce's
public demo instance). Offline, the e2e's stand-in SCAPI + SLAS answers the
storefront's calls from a three-product catalogue:
`node tests/web/fake-sfcc.mjs --port 4010 --client c --org o --site s`, then
`SFCC_CLIENT_ID=c SFCC_ORGANIZATIONID=o SFCC_SHORTCODE=x SFCC_SITEID=s
SFCC_API_ORIGIN=http://127.0.0.1:4010` (`SFCC_API_ORIGIN` is the test-only
override of `https://<short code>.api.commercecloud.salesforce.com`).

## How it maps to Vercel

| Vercel | Here |
|---|---|
| Next.js hosting (SSR, server actions, route handlers, `next/og`) | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets (`ASSETS`) |
| Cache Components with `"use cache"`, `cacheLife` and `cacheTag` | `"use cache"`, its lifetimes and its tags kept through `experimental.useCache`; every route renders per request from those cached reads |
| Data Cache entries | The R2 bucket bound as `NEXT_INC_CACHE_R2_BUCKET` |
| `revalidateTag` | A sharded Durable Object tag cache (`NEXT_TAG_CACHE_DO_SHARDED`) consulted on every cache read |
| Stale-while-revalidate | A Durable Object queue (`NEXT_CACHE_DO_QUEUE`) that re-renders stale entries through the Worker's `WORKER_SELF_REFERENCE` binding |
| Image Optimization | Off (`images.unoptimized`): images come from the instance's image URLs |
| `SFCC_CLIENT_ID`, `SFCC_ORGANIZATIONID`, `SFCC_SHORTCODE`, `SFCC_SITEID` | Orun secrets (optional build env) — and, unset, the "connect your Salesforce Commerce Cloud store" storefront instead of a build that throws on every read |
| `SFCC_SECRET`, `SFCC_REVALIDATION_SECRET` | Orun secrets each deploy puts on the Worker; the build never sees them. Without the first the client is public (PKCE); without the second the route answers 503 |
| `VERCEL_PROJECT_PRODUCTION_URL` | Each environment's `SITE_URL`, else its workers.dev URL, set by the build as `NEXT_PUBLIC_SITE_URL` |
| Deploy on push | Orun applies the bucket and deploys `<repo>-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`) |
| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, deployed |

Cache Components are off: `@opennextjs/cloudflare` 1.20 cannot run Next 16's
Cache Components on workerd yet (a Cache Components page answers 500 and then
hangs — opennextjs-cloudflare#1450), so the storefront keeps upstream's
`"use cache"` reads through `experimental.useCache` and renders every route at
request time. The epic's [IMPLEMENTATION-STATUS](specs/epics/sfcc-commerce/IMPLEMENTATION-STATUS.md)
has the evidence.

## How the bucket reaches the Worker

```
infra/terraform/cloudflare-r2 ──apply (r2-data token)──► orun secret WIRING_CLOUDFLARE_R2 (stage, prod)
│ (each deploy resolves it as it starts;
│ a missing one fails the lane)
▼
apps/web dependsOn cloudflare-r2 (enforced on main) · secretEnv WIRING_CLOUDFLARE_R2_<ENV>
build: tooling/wire/live.mjs → wrangler.jsonc with the environment's bucket name
(dev, verify-only, renders the fixture) → next build → opennextjs-cloudflare
→ tooling/wire/worker-secrets.mjs puts SFCC_SECRET, SFCC_REVALIDATION_SECRET on the Worker
deploy: workers-deploy token → <repo>-web-<env>, its Durable Objects migrated on first deploy
```

`wrangler.jsonc` is committed as the fixture render of
`wrangler.template.jsonc`, because the deploy lane's `verify-app-structure`
step checks the config exists before it builds; `testing/e2e.test.sh` fails
if the two disagree.

## CI

| Workflow | What it runs | Ships to a product |
|---|---|---|
| `ci.yml` | the Orun pipeline, and the only workflow a product carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the R2 root planned for stage and prod, the storefront built and dry-deployed per environment; they neither lint nor run the tests, which `baseline.yml`'s e2e tier runs before every tag), except the bootstrap's own landings (`orun/BASE-*`), where `plan` alone runs and nothing waits for it (the landing checked its commit in the box); a merge applies the R2 bucket, then deploys stage → prod. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does. A manual run (Orunbase's Deploy button, or Run workflow on `main`) plans the environment and components it names under the push-to-main trigger, so they deploy as a merge deploys them | yes |
21 changes: 21 additions & 0 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Local settings for `pnpm dev` (copy to .env.local) — a deployed storefront
# reads these from the environment's Orun secrets instead (component.yaml).
#
# The store: your SLAS client and site. Salesforce's public demo instance
# (the PWA Kit demo backend) works with these values and no secret:
# SFCC_CLIENT_ID=c9c45bfd-0ed3-4aa2-9971-40f88962b836
# SFCC_ORGANIZATIONID=f_ecom_zzrf_001
# SFCC_SHORTCODE=8o7m175y
# SFCC_SITEID=RefArchGlobal
# Left empty, the storefront renders and says how to connect a store.
SFCC_CLIENT_ID=""
SFCC_ORGANIZATIONID=""
SFCC_SHORTCODE=""
SFCC_SITEID=""
# A private SLAS client's secret; empty for a public client (PKCE guest login).
SFCC_SECRET=""
# The `?secret=` app/api/revalidate requires; empty turns revalidation off.
SFCC_REVALIDATION_SECRET=""
# The footer's copyright holder (defaults to the site's name).
COMPANY_NAME=""
NEXT_PUBLIC_SITE_URL="http://localhost:3000"
49 changes: 49 additions & 0 deletions apps/web/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage
.playwright

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# local env files
.env*
!.env.example

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
.env*.local

# editors
.cursor

# Cloudflare Workers: OpenNext's build, wrangler's local state and secrets
/.open-next/
/.wrangler/
/.turbo/
.dev.vars
.dev.vars.*
6 changes: 6 additions & 0 deletions apps/web/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Generated, with their generators' own layout: wrangler.jsonc is the
# template rendered (`pnpm run wire:fixture`), docs/ is the component's
# generated pages; both carry names a new product's rename makes longer.
wrangler.jsonc
wrangler.template.jsonc
docs/
47 changes: 47 additions & 0 deletions apps/web/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# apps/web — the storefront

Vercel's Next.js Commerce for Salesforce Commerce Cloud (MIT, `license.md`)
on Cloudflare Workers + Static Assets: server components over Salesforce B2C
Commerce's Shopper APIs, every shopper a SLAS guest, a server-action cart and
checkout kept in your instance's basket, `"use cache"` reads revalidated by
tag. The upstream pages and components are kept; what this app adds is the
Workers build, the cache bindings, a storefront that says how to connect a
store while none is, a secret-checked revalidation route and `/api/health`.

- `app/` — the routes: home, `/search`, `/search/<category>`,
`/product/<id>`, the content pages (`[page]`), `/checkout` (information,
shipping, payment) and `/checkout/confirmation`, the Open Graph images,
`robots.txt`, `sitemap.xml`, `/api/revalidate` and `/api/health`
- `app/site.ts` — the store's name and the repository its footer links to
- `lib/sfcc/` — the SCAPI client (`commerce-sdk-isomorphic`), the SLAS guest
login (a public client's PKCE flow, or a private client's secret), the
cached readers and their tags, the cart and checkout calls, the reshaping
to the page's types, and the revalidation route's logic; `connection.ts`
says whether a store is connected, and while none is every reader answers
empty without a call
- `components/` — cart (server actions, modal), checkout forms, navbar,
grid, carousel, product gallery and variants, the connect-store note

```bash
pnpm dev # next dev on http://localhost:3000
pnpm build # next build --webpack + opennextjs-cloudflare build → .open-next/
pnpm test # upstream's check: the prettier format check
pnpm preview # wrangler dev over the built Worker: a local R2 bucket, local Durable Objects
```

The cache's bucket is not hand-written. `wrangler.template.jsonc` names it as
a wiring token; `wrangler.jsonc` is that template rendered from
`wiring.fixture.json` (placeholder names, for local work and verification),
and every deploy renders it again from the name the `cloudflare-r2` Terraform
root published for the environment (`component.yaml`'s `buildCommand`).

## Store backend

| The four `SFCC_*` coordinates | catalogue | cart and checkout |
| ----------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| unset (a fresh deploy) | empty; `/` says "Connect your Salesforce Commerce Cloud store" and every page carries the note | none |
| set (read by the build) | the Shopper APIs, cached in R2 (`"use cache"`), revalidated through `/api/revalidate` | the instance's own basket and order, per shopper |

Connecting a store is four Orun secrets and a redeploy (five for a private
SLAS client), and revalidation one more — the repository's README,
"Connecting Salesforce Commerce Cloud".
12 changes: 12 additions & 0 deletions apps/web/app/[page]/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import Footer from "components/layout/footer";

export default function Layout({ children }: { children: React.ReactNode }) {
return (
<>
<div className="w-full">
<div className="mx-8 max-w-2xl py-20 sm:mx-auto">{children}</div>
</div>
<Footer />
</>
);
}
17 changes: 17 additions & 0 deletions apps/web/app/[page]/opengraph-image.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import OpengraphImage from "components/opengraph-image";
import { getPage } from "lib/sfcc/content";

export default async function Image({
params,
}: {
params: Promise<{ page: string }>;
}) {
const { page: handle } = await params;
const page = getPage(handle);

if (!page) return;

const title = page.seo?.title || page.title;

return await OpengraphImage({ title });
}
50 changes: 50 additions & 0 deletions apps/web/app/[page]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { Metadata } from "next";

import Prose from "components/prose";
import { getPage } from "lib/sfcc/content";
import { notFound } from "next/navigation";

export async function generateMetadata(props: {
params: Promise<{ page: string }>;
}): Promise<Metadata> {
const params = await props.params;
const page = await getPage(params.page);

if (!page) return notFound();

return {
title: page.seo?.title || page.title,
description: page.seo?.description || page.bodySummary,
openGraph: {
publishedTime: page.createdAt,
modifiedTime: page.updatedAt,
type: "article",
},
};
}

export default async function Page(props: {
params: Promise<{ page: string }>;
}) {
const params = await props.params;
const page = await getPage(params.page);

if (!page) return notFound();

return (
<>
<h1 className="mb-8 text-5xl font-bold">{page.title}</h1>
<Prose className="mb-8" html={page.body} />
<p className="text-sm italic">
{`This document was last updated on ${new Intl.DateTimeFormat(
undefined,
{
year: "numeric",
month: "long",
day: "numeric",
},
).format(new Date(page.updatedAt))}.`}
</p>
</>
);
}
12 changes: 12 additions & 0 deletions apps/web/app/api/health/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { isSFCCConfigured } from "lib/sfcc/connection";
import { NextResponse } from "next/server";

// The deploy's smoke check, and a quick way to tell whether this build has a
// store: the Worker answers it (no static file can), and it reads nothing
// from Salesforce.
export async function GET(): Promise<NextResponse> {
return NextResponse.json(
{ ok: true, connected: isSFCCConfigured() },
{ headers: { "cache-control": "no-store" } },
);
}
6 changes: 6 additions & 0 deletions apps/web/app/api/revalidate/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { revalidate } from "lib/sfcc";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest): Promise<NextResponse> {
return revalidate(req);
}
13 changes: 13 additions & 0 deletions apps/web/app/checkout/(main)/information/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { InformationForm } from "@/components/checkout/information-form";
import { getCart } from "@/lib/sfcc";
import { redirect } from "next/navigation";

export default async function InformationPage() {
const cart = await getCart();

if (!cart || cart.lines.length === 0) {
redirect("/");
}

return <InformationForm />;
}
Loading
Loading