Asia/Karachi
BlogNovember 14, 2026

E-Commerce Developer Reference Guide: Parts of a Store

What an online store consists of, and what to get right in each part
Fawaz Israr
E-Commerce Developer Reference Guide: Parts of a Store
An online store is a handful of parts that all depend on one thing: records that stay correct when two people click at once. The parts are a catalog, search, a cart, checkout and payments, orders, inventory, shipping and tax rules, customer accounts, emails, an admin panel, product pages that load fast and can be found, and the security and monitoring around all of that. This e-commerce developer reference guide goes through each part, says what to get right, and links deeper posts. Keep it open while you build. If you are a shop owner choosing a platform, my e-commerce website development guide is the better starting point. This one is for the person writing the code. Each layer has its own failure mode. The catalog fails when the data model cannot express how you really sell. The buying flow fails when the server trusts the browser. The back office (orders, stock, customers, emails, admin) fails when two actions collide or nobody can see what happened. Discovery fails quietly, as traffic you never get. Most store bugs come down to money as a float, a stock count changed without a guard, or an event processed twice. The sections below keep returning to those. Separate the product from the thing you actually sell. A product is a T-shirt with a title, description and images. A variant is a size and colour combination with its own SKU, price and stock. The cart, the order line and the stock count all point at the variant, never at the product. Store prices as integers in the smallest currency unit, and keep the currency code next to the amount. Binary floating point cannot represent 0.10 exactly, and the errors appear when you add up a cart. Not every currency has two decimal places, so format with Intl.NumberFormat using the currency code instead of dividing by 100 everywhere. Here is a Postgres fragment that covers the core tables. The users table is left out.
Sql
CREATE TABLE products (
  id          BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  slug        TEXT NOT NULL UNIQUE,
  title       TEXT NOT NULL,
  description TEXT NOT NULL DEFAULT '',
  is_active   BOOLEAN NOT NULL DEFAULT TRUE,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE variants (
  id             BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  product_id     BIGINT NOT NULL REFERENCES products(id),
  sku            TEXT NOT NULL UNIQUE,
  options        JSONB NOT NULL DEFAULT '{}',
  price_minor    INTEGER NOT NULL CHECK (price_minor >= 0),
  currency       CHAR(3) NOT NULL,
  stock_on_hand  INTEGER NOT NULL CHECK (stock_on_hand >= 0),
  stock_reserved INTEGER NOT NULL DEFAULT 0 CHECK (stock_reserved >= 0),
  CHECK (stock_reserved <= stock_on_hand)
);
CREATE INDEX ON variants (product_id);

CREATE TABLE orders (
  id          BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id     BIGINT NOT NULL REFERENCES users(id),
  status      TEXT NOT NULL DEFAULT 'pending_payment'
              CHECK (status IN ('pending_payment','paid','packed','shipped',
                                'delivered','cancelled','refunded')),
  currency    CHAR(3) NOT NULL,
  total_minor INTEGER NOT NULL CHECK (total_minor >= 0),
  paid_at     TIMESTAMPTZ,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- A snapshot of what was sold, so later price edits cannot rewrite history.
CREATE TABLE order_items (
  id               BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  order_id         BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
  variant_id       BIGINT REFERENCES variants(id) ON DELETE SET NULL,
  sku              TEXT NOT NULL,
  title            TEXT NOT NULL,
  unit_price_minor INTEGER NOT NULL CHECK (unit_price_minor >= 0),
  quantity         INTEGER NOT NULL CHECK (quantity > 0)
);
CREATE INDEX ON order_items (order_id);
Two details matter here. The order item copies the title, SKU and unit price, because a paid order from last month must still show what the customer paid. And deleting a product should usually mean setting is_active to false. I walk through the same model as a Prisma schema in Prisma schema design for e-commerce. Images belong in object storage, with only the URL, alt text and sort order in the database. Categories are a tree (a parent id column is enough), and a product may sit in several. For search and filtering, a small catalog is fine with indexed filter columns and a full-text query. Move to a search engine when you need typo tolerance, relevance ranking or fast facet counts across many thousands of products. Either way, every filter state should live in the URL, so a filtered page can be linked, reloaded and handled deliberately by search engines.
A hand holds a Visa payment card against a white square card reader, with tools and small metal parts blurred on a dark surface behind it.
The cart has two homes. Guest carts can live in the browser (local storage or a cookie), and logged-in carts live on the server so they follow the customer between devices. When a guest logs in, merge the two: add quantities for matching variants, cap each line at available stock, and delete the guest cart so it is not merged twice. For the client side, see a Redux Toolkit shopping cart. Whatever the client stores, the server must never trust it for money. The browser may send variant ids and quantities. The server looks up the current price, applies discounts, computes tax and shipping, and produces the total. Stripe Checkout in a MERN stack app shows this in a working integration. Use a hosted payment page or the provider's embedded payment fields. Card details then go straight to the provider and your server never touches them, which keeps your PCI scope small. Your server creates the session, redirects, and waits to be told what happened. That last part is the webhook. Do not mark an order paid because the customer landed on a success page: they can close the tab or open the URL by hand. Per Stripe's webhook documentation, verify the Stripe-Signature header against the raw request body, return a 2xx quickly, and expect duplicates and out-of-order events. Stripe suggests logging the event ids you have processed. For Checkout, its fulfillment guide names checkout.session.completed and, for delayed payment methods, checkout.session.async_payment_succeeded.
Ts
import Stripe from "stripe";
import { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma"; // your Prisma client instance

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST(req: Request) {
  const rawBody = await req.text(); // must be the unparsed body
  const signature = req.headers.get("stripe-signature");
  if (!signature) return new Response("Missing signature", { status: 400 });

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(
      rawBody,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!
    );
  } catch {
    return new Response("Invalid signature", { status: 400 });
  }

  if (
    event.type === "checkout.session.completed" ||
    event.type === "checkout.session.async_payment_succeeded"
  ) {
    const session = event.data.object as Stripe.Checkout.Session;
    const orderId = session.client_reference_id;

    // Delayed methods report "unpaid" here; the async event arrives later.
    if (session.payment_status === "paid" && orderId) {
      try {
        await prisma.$transaction(async (tx) => {
          // The primary key on event id rejects a duplicate delivery.
          await tx.webhookEvent.create({
            data: { id: event.id, type: event.type },
          });
          // Only a pending order may become paid.
          await tx.order.updateMany({
            where: { id: orderId, status: "PENDING_PAYMENT" },
            data: { status: "PAID", paidAt: new Date() },
          });
        });
      } catch (err) {
        if (
          err instanceof Prisma.PrismaClientKnownRequestError &&
          err.code === "P2002"
        ) {
          return new Response("Already processed", { status: 200 });
        }
        return new Response("Processing failed", { status: 500 }); // Stripe retries
      }
    }
  }

  return new Response(null, { status: 200 });
}
This assumes a WebhookEvent model whose id is the primary key, and an order whose id you passed as client_reference_id when you created the session. Send emails and other slow work to a queue after the transaction. Idempotency also applies in the other direction: when your server calls Stripe to create something, pass an idempotency key (the Idempotency-Key header, or the idempotencyKey request option in the Node library) so a retry after a network error does not create a second charge. Stripe allows keys of up to 255 characters. Model an order as a state machine with a short list of legal moves. A typical one is pending payment, paid, packed, shipped, delivered, with cancelled and refunded as exits from the right places. Enforce them in one function. The conditional updateMany above is the cheapest form of this: the update only matches an order that is still pending, so a second webhook or a double-clicked admin button changes nothing. Keep an order history table (old status, new status, who, when), because support questions are always about what happened. Overselling is a race condition. Two customers read a stock of one, both see it available, both buy. The fix is to let the database decide. Make the check and the change one statement:
Sql
-- Reserve units only if enough are free. Zero rows updated means sold out.
UPDATE variants
SET    stock_reserved = stock_reserved + :qty
WHERE  id = :variant_id
  AND  stock_on_hand - stock_reserved >= :qty;
Reserve stock when the order is created (holding it for a customer who has started to pay), release if the payment fails or the session expires, and convert the reservation into a real decrement when payment succeeds. Abandoned carts need an expiry job to release their holds. My multi-vendor architecture post covers how stock and sub-orders work when several sellers share a platform. Shipping and tax are rules engines, so keep them as data and small pure functions that you can test, not as numbers scattered through the UI. Shipping usually depends on destination, weight or order value. The cart in My-Shop handles automated tax calculation, dynamic shipping rules and discounts, which is the kind of logic that benefits from this separation. Tax and compliance rules vary by country and by what you sell, so get that part checked by an accountant or a tax professional. I cannot tell you what applies to your store. Support guest checkout alongside accounts, and store only what you need. Hash passwords, never log them, and keep roles (customer, staff, admin, and vendor on a marketplace) in the database, checked on the server for every action. Role-based access control with Next.js and Prisma shows an implementation. GoCart, my final year multi-vendor platform, has customer, vendor and administrator roles built this way. Transactional emails (order confirmation, shipping update, password reset) should be sent from a background job with retries, triggered by the order status change. In GoCart I used Inngest for background automation. The checkout request should never wait for an email provider. The admin panel is where the store owner lives. It needs an order list with status filters, a way to move an order along its state machine, stock editing with a reason recorded, and product editing with a preview. It needs the same permission checks as the public API, since an unguarded admin route is the most valuable hole in the system. Render product pages on the server or at build time with revalidation, so crawlers get the full HTML. Give each product one stable, readable URL with its slug. Optimise images, with explicit width and height so the layout does not jump. Core Web Vitals explained covers the metrics worth watching. Add Product structured data as JSON-LD. Per Google's product snippet documentation, name is required, along with at least one of review, aggregateRating or offers. For an Offer, availability, price currency and a valid-until date are recommended. The price uses a period as the decimal separator, and availability is a schema.org URL such as https://schema.org/InStock. Since you store integers, convert on the way out. Merchant listings, for pages where people can buy, have more fields, so read that page too.
Ts
const price = (variant.priceMinor / 100).toFixed(2); // for two-decimal currencies

const jsonLd = {
  "@context": "https://schema.org/",
  "@type": "Product",
  name: product.title,
  image: product.imageUrls,
  sku: variant.sku,
  offers: {
    "@type": "Offer",
    url: `https://example.com/products/${product.slug}`,
    price,
    priceCurrency: variant.currency,
    availability:
      variant.stockOnHand - variant.stockReserved > 0
        ? "https://schema.org/InStock"
        : "https://schema.org/OutOfStock",
  },
};
Keep the markup truthful: same price and stock status as the visible page. Filters create many URLs for the same products. Google's guidance on faceted navigation recommends disallowing crawling of filter URLs in robots.txt when you do not need them in search, and says canonical tags work but are generally less effective over the long term. A common setup keeps category pages crawlable, blocks sort and multi-filter combinations, and puts a canonical tag on variant URLs pointing to the main product URL. Give every page of a paginated list its own canonical, and do not point them all at page one. For the metadata mechanics in Next.js, see technical SEO with metadata, sitemap and canonical. Start with scope. Using a hosted checkout or the provider's embedded fields means card numbers never reach your server, which narrows what PCI DSS requires of you. Exact obligations depend on your integration and provider, so read their guidance. Then the usual web basics, applied everywhere:
  • Escape output to prevent XSS, especially product descriptions, reviews and anything vendors can type.
  • Protect state-changing requests from CSRF (SameSite cookies plus tokens or origin checks), and exempt the webhook route, which authenticates with its signature instead.
  • Rate limit login, password reset, coupon entry and checkout creation.
  • Keep secrets in environment variables, separate for test and live, and rotate them after a suspected leak.
  • Validate every input on the server, including quantities (no negatives, no huge numbers).
Test the code where money and stock move. Unit tests cover price calculation, discount and tax functions, and the order state machine, since they are pure functions. Integration tests run against a real database to prove that two concurrent reservations for the last unit produce one winner. Replay the same webhook payload twice and assert that the order changes once. The Stripe CLI can forward test events to your local server. For errors, decide what the customer sees and what you see. The customer gets a plain message and a safe state: no charge without an order, and no order that looks paid when it is not. You get a structured log with the order id, the event id and the failing step, and an alert when webhook failures or checkout errors rise. Now and then, compare paid orders with the provider's records and look for old pending orders. Copy this into your project notes. Website launch checklist for SEO, security and speed has the general version for any site.
Text
E-commerce launch checklist

Data
[ ] Prices stored as integers with a currency code; no floats anywhere
[ ] Order items snapshot title, SKU and unit price
[ ] Backups on, and one restore tried

Buying flow
[ ] Server recomputes every price, discount, tax and shipping figure
[ ] Hosted checkout or embedded payment fields; no card data on my server
[ ] Webhook verifies signature on the raw body, returns 2xx fast
[ ] Duplicate webhook delivery tested: the order changes once
[ ] Idempotency keys on calls that create charges or sessions

Stock and orders
[ ] Reservation is a single conditional UPDATE, tested with concurrent buyers
[ ] Order status changes go through one function with legal transitions
[ ] Abandoned reservations expire and release stock

Discovery
[ ] Product pages server-rendered, one canonical URL each
[ ] Product JSON-LD matches the visible price and stock
[ ] Filter URLs handled (robots.txt or canonical), pagination crawlable
[ ] Sitemap submitted, robots.txt checked

Safety
[ ] Live and test keys separated; secrets only in environment variables
[ ] Rate limits on login, reset, coupons and checkout
[ ] Roles checked on the server, including every admin route
[ ] Error alerts reach a person; a test order placed in production
[ ] Tax, returns and legal pages reviewed with a professional
I am Fawaz Israr, a full stack developer in Rahim Yar Khan, Pakistan, a final-year Computer Science student, and I work in web development at Hadi Dev Lab. If you are planning an online store and want a second opinion on the data model, checkout or stock handling, you can message me on WhatsApp or email. You can also browse my work first, including the GoCart multi-vendor platform, or read more about me. Cover photo from Unsplash.
Share this post: