Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 55 ยท Authentication and Sessions

Authenticated Requests and Route Protection

See how a Shopify app protects every route: authenticate.admin in the React Router template, session storage with Prisma, iframe redirects and public routes, with a pipeline you can run.

You now know the pieces: a session token proves who is calling (Session Tokens for Embedded Apps), token exchange turns it into an access token (Token Exchange and Access Tokens), and the access token is online or offline (Online vs Offline Tokens). This lesson shows how those pieces are wired into every request so you do not repeat them in each route.

In the official Shopify app template (React Router), one call at the top of each protected loader or action does all of it: authenticate.admin(request). After a quick tour of what it does, we build a small pipeline in plain JavaScript that behaves the same way, so you can see each step and each failure path. The real template code is read-only here; the runnable parts are stand-ins.

Package names, helper names and defaults change between releases of the Shopify app packages. The shapes below match the template at the time of writing; always compare with the generated code in your own project.

What authenticate.admin does

You create the helpers once, in a file the template calls app/shopify.server.ts, by passing your credentials, scopes, URL and a session storage to shopifyApp(...). The result exposes authenticate, with entries for the admin, webhooks and more. A protected route then looks like this (read-only; it needs a real Shopify app to run):

TypeScript
// app/routes/app.products.tsx  (read-only sketch)
import type { LoaderFunctionArgs } from "react-router";
import { authenticate } from "../shopify.server";

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const { admin, session } = await authenticate.admin(request);

  const response = await admin.graphql(`#graphql
    query FirstProducts {
      products(first: 5) { nodes { id title } }
    }`);
  const { data } = await response.json();

  return { shop: session.shop, products: data.products.nodes };
};

Behind that one line, the library:

  1. Reads the session token (from the Authorization header for fetches, or from a query parameter on the first document load).
  2. Verifies it: signature, expiry, audience, shop.
  3. Looks up a stored session for that shop (and user, for online tokens).
  4. If there is none, performs token exchange and stores the result.
  5. Returns an admin client already configured with the access token and API version, plus the session.

If anything fails, it does not return. It throws a Response (a redirect or a 401), which React Router sends to the browser. That is why you can write straight-line code afterwards: reaching the next line means the request is authenticated.

flowchart LR
  R["Incoming request"] --> V{"Valid session token?"}
  V -- No --> X["Throw redirect or 401"]
  V -- Yes --> L{"Stored session?"}
  L -- No --> E["Token exchange, save"]
  L -- Yes --> OK["Return admin client + session"]
  E --> OK

The library either returns an authenticated context or throws a response; your code never sees a half-authenticated request.

Session storage with Prisma

Access tokens must outlive a single request, so the library needs somewhere to keep sessions. The template uses the Prisma storage adapter with a Session table. A trimmed schema looks like this (read-only):

PRISMA
model Session {
  id          String    @id
  shop        String
  state       String
  isOnline    Boolean   @default(false)
  scope       String?
  expires     DateTime?
  accessToken String
  userId      BigInt?
}

Each row is one session: an offline row per shop, plus an online row per signed-in user if you use online tokens. The template starts with SQLite so it works out of the box; for production see Databases and Session Storage in Production.

Session rows hold access tokens, so apply the storage habits from the previous lessons: restrict database access, consider encryption, and delete rows when the app is uninstalled.

Getting out of the iframe

An embedded app runs inside the Shopify admin's iframe. Some steps cannot happen there: a page that must show a top-level consent screen, or a redirect to a URL that refuses to be framed (many payment confirmation pages do). The library handles the common cases:

  • When it needs a fresh session token, it redirects through a small bounce page that lets App Bridge produce one, then comes back.
  • When you need to leave the iframe, use the redirect function that authenticate.admin returns instead of a plain redirect() from the router. It knows whether to navigate the iframe, break out of it, or send a normal 302 for non-embedded requests.

Using a plain router redirect for an external URL inside an embedded page typically leaves a blank frame, because the target site refuses to render inside Shopify's iframe.

Public routes

Not every route should be authenticated. Examples:

  • A health check for your host.
  • Your marketing page at /, shown when someone visits your app URL directly. In the template this route lets a shop domain be typed and uses login to start the flow.
  • Webhook endpoints, which use authenticate.webhook(request) (HMAC verification, see Verifying Webhook Signatures) instead of a session token.
  • Storefront-facing endpoints such as app proxies, which use their own signature (App Proxy and Storefront Pages).

The rule: every route is either authenticated by one of these checks or deliberately public, and the choice is explicit in the code. A route with neither is a bug waiting to be found.

A middleware pipeline stand-in

The first stand-in builds the same shape in plain JavaScript: a pipeline of small steps that either returns a context or returns a "thrown response" (a plain object here). Real sessions would be verified JWTs; to keep the focus on the flow, the stand-in uses simple tokens in a lookup table.

Node.js authenticate(): return a context or a response

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.

Shop B has no stored session, so its first request triggers one (stand-in) exchange; the second request reuses the stored session. Shop A never needed one.

Protecting every route by default

The weakness of "call authenticate.admin at the top of each route" is that someone forgets. In the template, all pages under /app share a parent layout route that authenticates once, and individual loaders call it again where they need the admin client. You can add your own safety net, for example a test that walks your route table and asserts that each route is on an allow-list of public paths or is covered by an authentication check.

The second stand-in does exactly that with a route table: it classifies each route and flags any route that is neither public nor protected.

Node.js Audit a route table for missing protection

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 audit finds the forgotten /api/export and the leftover /app/debug route. Real checks can be more detailed, but even this crude version catches the most dangerous mistake: an endpoint that returns merchant data with no authentication at all.

Common mistakes

  • Trusting the shop in the URL or body. The shop must come from the verified session token, never from a query string field the browser can edit.
  • Skipping authentication on "internal" endpoints that return merchant data. If the browser can reach it, anyone can.
  • Caching authenticated responses on a CDN. Mark them Cache-Control: private, no-store; the same rule the Laravel-based tutorials on this site use for per-user pages.
  • Calling the Admin API with an old stored token and ignoring a 401. Clear the session and let the library exchange again.
  • Using a different database record for each request, so tokens pile up. Replace by key.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the template, what does authenticate.admin(request) do when the session token is invalid?

    It throws a Response, which the router sends to the browser. Code after the call only runs for authenticated requests.
  2. 2. Where must the shop domain used for an API call come from?

    Anything the browser can edit can be forged. The shop must come from verified data.
  3. 3. Why use the redirect function returned by authenticate.admin instead of a plain router redirect for external URLs?

    Embedded apps live in an iframe. The helper chooses the right kind of redirect so the target page is not blocked from rendering in the frame.
  4. 4. Which routes should skip authenticate.admin?

    Webhooks verify an HMAC, app proxy requests verify a proxy signature, and a few pages are public on purpose. Each must be protected in its own way or explicitly public.

Summary

  • authenticate.admin(request) verifies the session token, finds or creates the stored session, and returns an admin client; on failure it throws a response.
  • Sessions live in a database table (Prisma in the template); they contain access tokens, so protect them.
  • Use the library's redirect helper to leave the iframe safely.
  • Webhooks and app proxies authenticate differently, and a few routes are public on purpose; no route should be accidentally open.
  • Take the shop from verified data only, and never cache authenticated responses publicly.

Next: GraphQL for Shopify Developers starts the Admin API chapter, now that every request can be authenticated.