Understanding Shopify OAuth 2.0: Session Tokens, Access Tokens, and Gotchas
A practical deep dive into Shopify's OAuth flow — JWT session token structure, online vs offline tokens, refresh race conditions, and the debugging tricks that save hours.
A practical deep dive into Shopify's OAuth flow — JWT session token structure, online vs offline tokens, refresh race conditions, and the debugging tricks that save hours.
This article is a collection of things I've learned the hard way. We'll look at what session tokens actually contain (not just "it's a JWT"), when to use online vs offline access tokens (spoiler: almost always offline), and a few bugs that only become visible when your app starts getting traffic.
Modern Shopify apps use two types of tokens for different purposes:
| Token Type | Lifetime | Use Case | Where Used | |---|---|---|---| | Access Token | Permanent (until revoked) | Server-to-server API calls | Backend only | | Session Token | 60 seconds | Authenticating embedded admin requests | Frontend → Backend |
The access token is the long-lived credential you get after the OAuth install flow. The session token is a short-lived JWT that the Admin frontend includes in every request to your app. You validate the session token to confirm the request came from a logged-in merchant.
A session token is a JWT (JWS, specifically) with this structure:
Header.Payload.Signature
Decoded payload:
{
"iss": "https://my-store.myshopify.com/admin",
"dest": "https://my-store.myshopify.com",
"aud": "your-api-key",
"sub": "",
"exp": 1726000060,
"nbf": 1726000000,
"iat": 1726000000,
"jti": "abc123-...",
"sid": "session-id"
}
Key fields to validate:
iss — Must match the .myshopify.com domain of the store. This is how you know which store the request is from.aud — Must match your app's API key (Client ID). Prevents token substitution attacks.exp — Expiry time. Session tokens are valid for 60 seconds.nbf — "Not before" — the token isn't valid before this time.Here's a real validation implementation:
import jwt from "jsonwebtoken";
// fetchShopifyCerts() retrieves Shopify's JWKS public keys from
// https://api.shopify.com/.well-known/jwks.json
import { fetchShopifyCerts } from "./shopify-certs";
export async function validateSessionToken(
token: string,
apiKey: string
): Promise<{ iss: string; dest: string }> {
// Fetch Shopify's public key for JWT verification
const key = await fetchShopifyCerts();
const decoded = jwt.verify(token, key, {
algorithms: ["RS256"],
audience: apiKey,
}) as { iss: string; dest: string };
// Verify the issuer is a valid .myshopify.com domain
if (!decoded.iss.endsWith(".myshopify.com/admin")) {
throw new Error(`Invalid token issuer: ${decoded.iss}`);
}
return { iss: decoded.iss, dest: decoded.dest };
}
During the OAuth flow, you choose between online and offline access tokens:
Offline tokens (recommended for most apps):
isOnline: false in the Shopify API libraryOnline tokens:
isOnline: trueMost apps should use offline tokens for API access and session tokens for admin UI authentication. A common mistake is requesting online tokens when you don't need them — this adds complexity without benefit.
// shopify-config.ts
const shopify = shopifyApp({
api: {
apiVersion: "2026-07",
// For most apps, offline is the right choice
isEmbeddedApp: true,
},
auth: {
path: "/auth",
callbackPath: "/auth/callback",
},
webhooks: {
path: "/webhooks",
},
});
Here's a problem that only shows up under load: when multiple requests arrive simultaneously with an expired session token, they all try to refresh at the same time. Without protection, you get:
The fix is a simple in-flight deduplication:
let refreshPromise: Promise<string> | null = null;
// AuthModule is your app's auth abstraction (e.g., from @shopify/shopify-app-remix)
// It exposes sessionToken and refreshSessionToken()
async function getSessionToken(auth: AuthModule): Promise<string> {
const currentToken = auth.sessionToken;
// If token expires in less than 10 seconds, refresh
if (isExpiringSoon(currentToken, 10_000)) {
// Reuse in-flight refresh if one is already happening
if (!refreshPromise) {
refreshPromise = auth
.refreshSessionToken()
.finally(() => {
refreshPromise = null;
});
}
return refreshPromise;
}
return currentToken;
}
function isExpiringSoon(token: string, bufferMs: number): boolean {
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString());
const expiresAt = payload.exp * 1000;
return Date.now() + bufferMs >= expiresAt;
}
The 10-second buffer prevents the edge case where the token expires between validation and use.
OAuth isn't just about tokens — you also need to verify that webhooks actually came from Shopify. Every webhook request includes an X-Shopify-Hmac-SHA256 header:
import crypto from "crypto";
export function verifyWebhookHmac(
body: string,
hmacHeader: string,
secret: string
): boolean {
const hash = crypto
.createHmac("sha256", secret)
.update(body, "utf8")
.digest("base64");
return crypto.timingSafeEqual(
Buffer.from(hash),
Buffer.from(hmacHeader)
);
}
Always use timingSafeEqual instead of === for HMAC comparison. Regular string comparison is vulnerable to timing attacks.
This one gets me every time. You add a new API scope to your app — say write_discounts — and deploy. Works perfectly on your dev store. But merchants who installed before the update? They authorized read_products and read_orders, not write_discounts. Their tokens don't have the new permission.
The fix is to check scopes on every request and redirect to re-authorize when they're missing:
const hasRequiredScopes = await shopify.session.hasScopes(
session,
["read_products", "write_discounts"]
);
if (!hasRequiredScopes) {
throw redirect(`/auth?shop=${shop}`);
}
I learned this after a merchant reported that discounts weren't being created. The app was silently failing on every API call because the token lacked write_discounts. The merchant had installed three months before we added that scope.
When a merchant uninstalls your app, Shopify sends an APP_UNINSTALLED webhook. If you don't handle it, your app keeps making API calls with a revoked token — generating errors, burning through rate limits, and filling your logs with 401s.
Handle it by clearing the store's credentials:
// webhooks/app-uninstalled.ts
export async function handleAppUninstalled(
shop: string,
db: Database
) {
await db.store.update({
where: { domain: shop },
data: {
accessToken: null,
status: "UNINSTALLED",
uninstalledAt: new Date(),
},
});
}
This is also a GDPR requirement — you need to stop accessing the store's data when they ask you to.
An access token is basically a skeleton key to the store's admin. Anyone with that token can read products, modify orders, change settings — everything the scope allows. Storing it in plaintext in your database is like leaving your front door key under the mat.
Encrypt at rest:
import crypto from "crypto";
const ALGORITHM = "aes-256-gcm";
export function encryptToken(plaintext: string, key: string): string {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv(ALGORITHM, Buffer.from(key, "hex"), iv);
let encrypted = cipher.update(plaintext, "utf8", "hex");
encrypted += cipher.final("hex");
const authTag = cipher.getAuthTag().toString("hex");
return `${iv.toString("hex")}:${authTag}:${encrypted}`;
}
The decryption key goes in your environment variables, not in your code. If someone gets your database dump but not your server's environment, the tokens are still useless.
Development stores don't behave like production stores. Tokens can expire unexpectedly when the store is paused or reset. The Shopify Partner dashboard might show the store as "active" even when it's in a weird state.
If you're getting sudden 401 errors in development:
SHOPIFY_API_KEY and SHOPIFY_API_SECRET match the current app configI've wasted entire afternoons debugging "broken" OAuth code that was actually just a paused dev store. Don't be me.
Decode session tokens in your browser console:
// Paste a session token to inspect it
const token = "eyJ...";
const payload = JSON.parse(atob(token.split(".")[1]));
console.table({
issuer: payload.iss,
audience: payload.aud,
expiresAt: new Date(payload.exp * 1000).toISOString(),
validFor: `${payload.exp - Math.floor(Date.now() / 1000)}s`,
});
Log token validation failures with context:
try {
await validateSessionToken(token, apiKey);
} catch (err) {
console.error("Token validation failed", {
error: err.message,
// extractIssuer decodes the JWT payload without verifying the signature
issuer: extractIssuer(token), // safe — doesn't require valid signature
apiKeyConfigured: !!apiKey,
timestamp: new Date().toISOString(),
});
throw new Response("Unauthorized", { status: 401 });
}
The race condition in token refresh and the scope-mismatch-after-install issue are the two things that caused the most pain after we launched Markdo. Both are simple to fix once you know they exist, and both are invisible until your app has real traffic and real merchants.
If you're building a Shopify app, test with at least two concurrent browser tabs hitting your endpoints. That's how I found the refresh race condition. And add a scope check to your middleware early — it takes five minutes and saves you from a confusing support ticket three months from now.