Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 28 ยท Apps and OAuth

Building an App Backend

Structure a BigCommerce app server: store tokens securely per store, handle the load callback and iframe, clean up on uninstall, and support several users.

The OAuth flow from the last lesson gets a token to your server. An app is everything that happens afterwards: keeping that token safe, answering the load callback with a page the merchant can use, reacting when someone uninstalls, and doing all of it for hundreds of stores at once without mixing them up. This lesson is about the shape of a sound app backend.

Real BigCommerce app code needs a registered app and a live store, so the framework skeleton here is read-only. The runnable stand-in is a small Node.js "mini app": a token store that encrypts tokens at rest, a verifier for the signed load payload, and a router for the callbacks. It runs entirely in memory, and it is a model of the structure, not a production server.

What the backend must do

An app backend has four responsibilities, and every design choice follows from them:

  1. Install: receive the auth callback, exchange the code, and save one token per store.
  2. Open: receive the load callback, verify the signed payload, and render the app inside the control panel.
  3. Work: use the stored token to call BigCommerce APIs for that store, and receive its webhooks.
  4. Leave: on uninstall, stop working for that store and delete what you hold.

The key mental model is multi-tenancy: your one server serves many stores. Every record you keep must carry the store hash, and every request must establish which store it is for before any data is read. Mixing up two stores is the worst bug an app can have.

flowchart TD
    BC["BigCommerce"] -->|"auth callback"| I["/auth<br/>exchange code, save token"]
    BC -->|"load callback<br/>signed_payload_jwt"| L["/load<br/>verify, render app"]
    BC -->|"uninstall callback"| U["/uninstall<br/>delete store data"]
    BC -->|"webhooks"| W["/webhooks<br/>queue and process"]
    I --> DB[("Token store<br/>per store hash")]
    L --> DB
    U --> DB
    W --> DB

One server, four entry points, and a single store-keyed data store.

A suggested server structure

Keep the code small and layered. A common layout for a Node app (read-only sketch, using Express-style routing for illustration):

JavaScript
// server.js: read-only skeleton, not runnable here
import express from "express";
import { verifyLoadPayload } from "./jwt.js";
import { tokens } from "./token-store.js";
import { exchangeCode } from "./bigcommerce.js";

const app = express();

app.get("/auth", async (req, res) => {
  const { code, scope, context } = req.query;
  const grant = await exchangeCode({ code, scope, context });
  await tokens.save(grant.context, grant.access_token, grant.scope, grant.user);
  res.redirect("/load-hint"); // or render a success page
});

app.get("/load", async (req, res) => {
  const claims = verifyLoadPayload(req.query.signed_payload_jwt);
  const store = await tokens.find(claims.sub);
  if (!store) return res.status(403).send("App is not installed for this store");
  res.render("app", { storeHash: store.hash, user: claims.user });
});

app.get("/uninstall", async (req, res) => {
  const claims = verifyLoadPayload(req.query.signed_payload_jwt);
  await tokens.remove(claims.sub);
  res.sendStatus(200);
});

The names exchangeCode, tokens and verifyLoadPayload are our own. The point is separation: callbacks parse and verify, a token store owns persistence, and a client module owns calls to the platform. The official sample apps use Next.js with an API layer and a database; the ideas are the same, and your framework choice is yours.

Storing store hashes and tokens

For each installed store keep at least: the store hash, the access token, the granted scopes, the installing user, the install time and an "active" flag. Rules that apply regardless of database:

  • Encrypt tokens at rest with a key held outside the database (a secret manager or environment variable). A leaked database backup should not equal leaked store access.
  • Never log tokens, secrets or signed payloads.
  • Index by store hash and make it part of every query's WHERE clause. Do not build "get token" helpers that take no store argument.
  • Keep the client secret out of source control. See Setting Up a Development Environment for env-file habits.

Rotating the encryption key is easier if you store a key version next to each ciphertext. The first stand-in below does that.

Node.js An encrypted token store, one record per store

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The saved value is unreadable ciphertext, each store gets its own record, and removing a store makes its token unavailable. AES-GCM also authenticates the data, so a modified record is refused instead of silently producing garbage. This is a model: in production use a database, a real key service and a key-rotation plan.

The load callback and the iframe

When a merchant opens your app, the control panel shows your load URL inside an iframe. Three consequences:

  • Your response is a normal web page, but it runs inside someone else's page. Your server must allow being framed by the control panel (a Content-Security-Policy: frame-ancestors rule listing the BigCommerce domains is the modern way; avoid the old blanket X-Frame-Options: DENY).
  • Third-party cookies are restricted in many browsers, so do not rely on a cookie set inside the iframe as your only session. A common pattern is to verify the signed payload on load and issue a short-lived session or token for your own API calls from the page.
  • The signed payload is verified on every load, not just the first, because it identifies who is opening the app right now. Verification steps are in App Types and the OAuth Flow.

For the look and feel, BigCommerce publishes BigDesign, a React component library that matches the control panel (buttons, tables, forms, panels). Using it is optional but makes your app feel native. It is a design-and-UI concern; the backend lessons here do not depend on it.

Multiple users and uninstall

Several people can work in one store, and the store owner decides who may open your app. Your records should therefore separate store (one token) from users (many people with their own access in your app). The load payload tells you the current user and whether they are the store owner. If you support the optional remove-user callback, delete or disable that user's access in your system when it fires.

On uninstall, do what you promised in your privacy policy: stop jobs for that store, delete the token, and remove or anonymize store data after any retention period you must keep. Handle the case where the callback never arrives (it can fail), by treating 401 or 403 responses from the API as a signal that the app is no longer authorized, and by making jobs skip stores marked inactive.

A mini app stand-in

The second stand-in wires the pieces: a router for auth, load, uninstall and remove_user events, a signed load payload verified with HS256, and an in-memory store. It tracks users separately from stores.

Node.js A mini app: install, open, remove a user, uninstall

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each event verifies the signed payload first, then touches only the record for the store named in it. The forged load request is refused with a clear error, the removed user disappears while the store stays installed, and after uninstall the same valid payload gets a 403 because no installation exists.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes an app backend multi-tenant safe?

    Establish which store a request is for, then use only that store's records. Mixing stores is the most damaging bug.
  2. 2. Why encrypt access tokens in your database?

    Tokens are bearer credentials. Encryption at rest with a separately held key limits the impact of a database leak.
  3. 3. Why is the signed payload verified on every load?

    Every load can come from a different user or from an attacker hitting your URL directly. The signature proves it came from the platform.
  4. 4. What should happen when the uninstall callback arrives?

    Honor the uninstall: stop jobs, delete credentials and clean data according to your policy.
  5. 5. Why avoid relying only on cookies inside the app iframe?

    Third-party cookie restrictions can break cookie-only sessions. Verify the payload on load and use a short-lived session or token you control.

Summary

  • An app backend installs, opens, works and leaves; every step is keyed by store hash.
  • Keep layers separate: callbacks verify, a token store persists, a client module calls the API.
  • Encrypt tokens at rest, never log them, and keep the client secret in the environment.
  • The load page runs in an iframe: allow framing, verify the signed payload each time, and do not depend only on third-party cookies.
  • Separate stores from users, honor the uninstall and remove-user callbacks, and treat 401/403 as a sign of lost access.

Next: Webhooks