MarcosCamara01/ecommerce-template
Acerca de
An ecommerce template built with NextJS 16, TypeScript and TailwindCSS
Negocios y finanzasWhat you can do
- Catalog with categories, variants, search, and help pages
- Cart and wishlist (session required; data is scoped to the signed-in Principal)
- Stripe Checkout from a server-built cart snapshot, not a client-supplied price
- Order history and a result page that only loads a session the buyer owns
Crecimiento de estrellas medido
- in 24h
- +1
- in 7 days
- +2
- in 15 days
- +3
- in 1 month
- Actualización retrasada
Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.
README.md
OriginalNext.js Ecommerce Template
Storefront starter with a public catalog, authenticated cart and checkout, Stripe fulfillment, and an admin catalog that stays in sync with Stripe. Built for App Router, a least-privilege Postgres layout, and a Principal-bound data layer.
Live demo: ecommerce-template-mpc.vercel.app
Stack
| Layer | Choice |
|---|---|
| App | Next.js 16.3 (App Router, Cache Components), React 19, TypeScript |
| UI | Tailwind CSS, Radix UI, TanStack Query |
| Auth | Better Auth (email/password; Google is opt-in) |
| Data | Drizzle ORM on Supabase PostgreSQL (app_private) |
| Payments | Stripe Checkout (server-priced line items) |
| Media | Supabase Storage (product-images: JPEG, PNG, WebP) |
| Resend HTTP API | |
| Validation | Zod |
Shared domain language lives in CONTEXT.md. Architecture and
invariants are in
docs/architecture/verifiable-auth-data-fulfillment.md.
Features
- Catalog with categories, variants, search, and help pages
- Cart and wishlist (session required; data is scoped to the signed-in Principal)
- Stripe Checkout from a server-built cart snapshot, not a client-supplied price
- Order history and a result page that only loads a session the buyer owns
- Admin product create/edit with Stripe catalog sync and replay for failed work
- Background fulfillment and catalog-sync crons (Vercel, every 5 minutes)
- Email verification before credential sign-in, and forgot/reset password
- Order-confirmation and merchant-notification email
Prerequisites
- Node.js 24 (what CI uses) and npm
- PostgreSQL 15 or newer, typically via Supabase
- A Stripe account, or the local Stripe emulator for development
Getting started
Install dependencies:
npm installCopy
.env.exampleto.env.localand fill the values described below.For a fresh database, bootstrap roles, migrate, verify, then promote the first admin. For a populated database, follow the database cutover runbook instead of applying ad-hoc schema changes.
npm run db:migrate npm run db:verify npm run auth:bootstrap-adminStart the app:
npm run devOpen http://localhost:3000.
db:push is disabled. Generate a reviewed migration with db:generate, apply
it with db:migrate.
Configuration
Keep NEXT_PUBLIC_APP_URL and BETTER_AUTH_URL on the same canonical origin.
APP_URL is an optional server-only override; when set, it must use that same
origin.
The complete list of variables is in .env.example. These are the ones that
decide how the app boots:
| Variable | Role |
|---|---|
DATABASE_URL |
Runtime connection as app_runtime |
MIGRATION_DATABASE_URL |
app_migrator; db:migrate then assumes app_owner |
VERIFY_DATABASE_URL |
Least-privileged connection for db:verify |
AUTH_DATABASE_LAYOUT |
Must be app_private |
BETTER_AUTH_SECRET |
Session signing secret |
ADMIN_USER_ID |
Better Auth user id promoted by auth:bootstrap-admin |
CRON_SECRET |
Bearer secret for /api/cron/* |
STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY |
Stripe |
NEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_ANON_KEY, SUPABASE_SERVICE_ROLE_KEY |
Storage and project URL |
SUPABASE_PROJECT_REF, SUPABASE_ACCESS_TOKEN |
Hosted Data API / Storage apply (db:apply-hosted) |
ADMIN_BOOTSTRAP_DATABASE_URL is only for the temporary legacy-public cutover
in the runbook. Do not put role= in MIGRATION_DATABASE_URL.
Auth
A credential account must confirm its email before it can sign in. Sign-up
mails a link and answers "check your email" whether or not the address already
has an account; the owner of a taken address gets a mail saying how to get in.
An unverified account that signs in with the right password is refused and
gets a new link. Links last an hour, and every outcome of a link (verified,
expired, already used) lands on /email-verification. Opening a link confirms
the email but signs nobody in: a link opened in someone else's browser would
otherwise sign that browser into the registrant's account.
/forgot-password answers the same for any address. A reset signs the
account out everywhere and also confirms the email, because the link reached
the mailbox. Resending a link by address alone is off
(/api/auth/send-verification-email answers 404): signing in again or a reset
sends a new one.
Sign-up, forgot and reset are server actions in src/app/(auth)/actions.ts
and work without JavaScript. They reach Better Auth through auth.handler,
not auth.api, so its rate limiter and origin check still apply. Sign-in stays
on the Better Auth client, with /api/auth/email-form as its no-JS fallback.
Auth mail is sent after the response, so its latency does not reveal whether
an account exists. Google sign-ups are verified by Google and get no mail.
Sessions opened before verification was required stay valid until they end or the account's password is reset.
Google sign-in is opt-in. Register the exact callback
http://localhost:3000/api/auth/callback/google (and the HTTPS production
equivalent) in Google Cloud, set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET,
then set both GOOGLE_AUTH_ENABLED=true and
NEXT_PUBLIC_GOOGLE_AUTH_ENABLED=true. The server fails closed when the flags
differ. Keep both false until the callback is registered.
OAuth cannot reclaim or rewrite an unverified credential account. Linking another provider still requires the existing local account to be verified.
Promote the first administrator by user id, not by email. Credential sign-in requires a verified email, and the operator vouches for this account, so the script also marks its email verified:
ADMIN_USER_ID=<better-auth-user-id> npm run auth:bootstrap-admin
Mail goes through Resend's HTTP API. Set RESEND_API_KEY and EMAIL_FROM
(Store <[email protected]>; the domain must be verified in
Resend). Owner notices go to EMAIL_CONTACT_TO, or ADMIN_EMAIL when it is
unset; no other mail needs a contact address.
Under next dev without a key, every message, verification and reset links
included, is printed to the terminal instead of sent. Without mail, nobody can
confirm a new account, so set the key before a production launch. A production build never falls back: without a key, sends
fail as email_not_configured, and order mail goes to needs_attention for
an admin replay once the key is set.
Order mail is at least once. Each send carries the effect's key as Resend's
Idempotency-Key, scoped to the store's host, so a resend within 24 hours is
not delivered twice. Refusals that no retry can fix (a bad key, an unverified
domain, a spent quota) go straight to needs_attention; rate limits, outages,
and timeouts retry.
Local Stripe
In development, set STRIPE_EMULATOR_URL to a loopback HTTP origin (no path,
credentials, or query). Example:
npx emulate --service stripe
Then point STRIPE_EMULATOR_URL at the emulator origin (default
http://localhost:4000 when Stripe runs alone). The variable is rejected in
NODE_ENV=production.
The live webhook endpoint is /api/stripe/webhooks.
Scripts
| Script | Purpose |
|---|---|
npm run dev |
Next.js dev server |
npm run build / npm start |
Production build and server |
npm test |
Node.js test runner |
npm run test:e2e |
End-to-end tests in a browser; see End-to-end tests |
npm run lint |
ESLint |
npm run typecheck |
tsc --noEmit |
npm run verify:architecture |
Import-boundary and layering checks |
npm run verify:release |
Production evidence gate |
npm run db:generate |
Drizzle Kit migration |
npm run db:migrate |
Role-aware migrator (app_migrator → app_owner) |
npm run db:verify |
Schema and privilege verifier |
npm run db:apply-hosted / db:verify-hosted |
Push and check Supabase Data API, Auth sign-up, and product-images |
npm run db:mark-cutover |
Record applied migrations after a cutover |
npm run db:studio / db:pull |
Drizzle Kit as app_owner via the migrator session |
npm run auth:bootstrap-admin |
Grant admin to ADMIN_USER_ID and mark its email verified |
npm run doctor |
React Doctor on the full tree |
db:migrate authenticates as app_migrator, proves that role cannot run
private DDL directly, then SET ROLE app_owner before applying the official
Drizzle journal.
db:apply-hosted uses the lockfile-pinned Supabase CLI to push
supabase/config.toml to SUPABASE_PROJECT_REF, which exposes no Data API
schema and closes GoTrue sign-up (Better Auth owns accounts). It then runs
db:verify-hosted, which checks, read-only, the Data API allowlist,
disable_signup, the public product-images bucket (5 MiB, JPEG/PNG/WebP), and
that storage.objects carries only the public read policy from
supabase/migrations/20261122000000_product_images_storage_policies.sql. No
client role can write Storage; the app uploads with the service role. Run that
SQL once as postgres (SQL editor) before db:apply-hosted. Both commands
need SUPABASE_ACCESS_TOKEN and SUPABASE_SERVICE_ROLE_KEY. The service-role
key is withheld from the CLI config-push subprocess.
End-to-end tests
tests/ holds a browser suite written with e2e,
and an agent does most of it. A test says what a shopper wants ("add this piece
to the bag in size M"); the agent does it in a real browser and is then asked
whether it happened. No goal says how a page is built and no check names a
label of it, so a redesign that keeps the store working keeps the suite green.
- What the shopper sees is judged by the agent, in words.
- What the store recorded (the lines of a bag, a saved piece, who is signed in) is read from its API and compared exactly: money and quantities are not left to a model.
- A few tests are exact from end to end, because the exact interface is their subject: the keyboard, focus, notices that come and go, who may see what. Those name today's labels and say so.
It assumes no catalog: it reads the pieces the store shows and works with those.
The agent is Claude, through the Claude Code CLI and the account claude is
signed in to (the bridge); no key is involved.
The first run asks the model for every goal. A goal whose outcome was confirmed
is recorded in .e2e/cache/ and replayed afterwards without the model, which
takes over again only where the interface has changed. The judgments are asked
on every run: about 75 calls and four to five minutes for the whole suite.
Start the store, then run the suite against the origin the store is served
from (APP_URL; the proxy redirects any other host):
E2E_APP_URL=http://localhost:3000 npm run test:e2e
| Variable | Effect |
|---|---|
E2E_APP_URL |
The store under test. Default http://localhost:3000. |
E2E_ALLOW_WRITES=1 |
Also runs the tests that sign up shoppers, fill bags and save pieces. Only against a disposable database. Without it a run changes nothing. New shoppers confirm their email with a link minted from BETTER_AUTH_SECRET, which must be the app's own. |
E2E_USER_CUSTOMER_USERNAME, E2E_USER_CUSTOMER_PASSWORD |
A shopper with past orders, for the order pages. |
E2E_USER_ADMIN_USERNAME, E2E_USER_ADMIN_PASSWORD |
An admin, for the product forms. They are opened, never saved. |
E2E_MODEL |
The model the CLI runs. Default sonnet. |
- The tests tagged
agentneed the CLI. The rest need nothing:npm exec -- e2e run --exclude-tag agent. - The catalog needs pieces in every section, in stock in two sizes. The tests of colors and of the photo viewer skip when no piece has them.
- The cards of a listing are read straight from the page. If a redesign leaves that reading with nothing, the agent reads the listing instead; the suite gets slower, not red.
- A production build allows three sign-ins every ten seconds. The suite opens its sessions through the auth API and waits a refusal out.
- Checkout is covered up to the hand-off: the test stands in for Stripe.
- A run writes its report, traces and replay cache to
.e2e/, which is ignored.
Architecture
src/lib/identity is the only request-credential boundary. It returns opaque
user Principals (or purpose-limited system Principals for fulfillment and
catalog sync). UI role checks are advisory; writes repeat the authoritative
check.
src/lib/data-access is the application interface to repositories. Public
catalog reads are separate from Principal-bound cart, wishlist, order,
checkout, and admin operations.
Checkout persists a server-created snapshot (at most 100 lines). Stripe metadata holds only an opaque checkout-intent id. Fulfillment reconciles the charged amount against that snapshot; the live cart is never a fulfillment input. Webhooks record an event receipt and work row, then a worker (or the 5-minute cron) completes the order.
Deployment
- Set every required variable in the host (Vercel Production, Preview, and Development as needed).
- Point Stripe webhooks at
https://<origin>/api/stripe/webhooks. - Run
npm run db:migratebefore shipping code that depends on a new schema. - Never use
db:push. - Better Auth rate-limits by the client IP in
X-Forwarded-For. Vercel overwrites that header with the caller's address, so a client cannot rotate it to dodge the limit. Behind any other proxy, setadvanced.ipAddress.ipAddressHeadersinsrc/utils/auth.tsto a header that proxy sets and strips from incoming requests. - Production builds run
npm run verify:releaseand fail untilRELEASE_CUTOVER_EVIDENCE,RELEASE_HOSTED_EXPOSURE_EVIDENCE, andRELEASE_CREDENTIAL_ROTATION_EVIDENCEpoint at the approved restore rehearsal, hosted exposure report, and credential-rotation audit. - Vercel crons call
/api/cron/fulfillmentand/api/cron/catalog-syncevery five minutes. The only credential they accept isAuthorization: Bearer <CRON_SECRET>, which Vercel sends whenCRON_SECRETis set. Any client can sendx-vercel-cron: 1, so that header alone gets a- Without
CRON_SECRETboth answer 503.
- Without
CI
Pull requests run .github/workflows/ci.yml: tests, a PostgreSQL 15 cutover
rehearsal, typecheck, lint, architecture and release-gate checks, next build,
and npm audit (all dependencies and production-only).
License
MIT. See LICENSE.
Explorar proyectos relacionados
Cargando…