App/uninstalled and compliance webhooks return 500 after enabling expiring offline access tokens

We recently enabled expiring offline access tokens (future: { expiringOfflineAccessTokens: true }) in our React Router app, as required for public apps.

Since then, our app/uninstalled and mandatory compliance webhooks (shop/redact etc.) fail with a 500 on every delivery and retry. All other webhooks work fine, and bad-HMAC requests correctly get a 401. Our handlers follow the template docs exactly, including the if (!session) check.

What we found: authenticate.webhook() tries to refresh the shop’s access token before our handler code runs. But when a shop uninstalls, Shopify revokes their tokens - so the refresh can never succeed, and the library responds with a 500 instead of continuing with session: undefined like the docs describe. Our handler never runs, so we never get to return the 200.

It only happens when the stored token is already stale (shop idle for an hour or more before uninstalling). Uninstalling right after using the app works fine - which is why our own testing never caught it, but the app review store hit it.

Reproduce:

  1. Enable expiringOfflineAccessTokens
  2. Install the app, don’t touch it for an hour
  3. Uninstall without opening the app
  4. app/uninstalled → 500, and shop/redact later fails the same way

This is a problem for app review, since compliance webhooks must return a 200.

Has anyone else run into this since switching to expiring tokens? Is there a recommended way to handle webhooks for shops whose tokens are already revoked?

Or are we doing something completely wrong here?

export const action = async ({ request }: ActionFunctionArgs) => {
  const { shop, session, topic } = await authenticate.webhook(request);

  console.log(`Received ${topic} webhook for ${shop}`);

  if (!session) {
    return new Response();
  }

  await db.session.deleteMany({ where: { shop } });

  return new Response();
};

Hey @James_A - thanks for flagging this and for theeproduction steps. I’m going to raise this internally. I’ll keep you in the loop and follow up here once I have more information.

Not a React Router app here (Python backend), so I can’t speak to
the library internals. But I hit the same wall during review and I
think the fix is architectural rather than a workaround.

The thing that unblocked it for me: HMAC verification uses the
app’s client secret, not the shop’s access token. And topic, shop
domain and webhook id all arrive in the headers. So a compliance
or uninstall handler never needs a session at all - it can verify
and dispatch without touching the token.

app/uninstalled is the clearest case. The token is revoked by
definition when that fires. Any code path that tries to refresh
before the handler runs is guaranteed to fail on the one topic
where it matters most.

What I do:

  • verify HMAC against the client secret, 401 if it fails
  • read topic and shop from headers, never parse the body for routing
  • return 2XX for unknown or dummy shops after a valid HMAC. The
    automated review test sends one, and a 404 there fails review
  • keep session-dependent auth on data-access routes only

One thing I’d keep though - if your database is down, return 500,
not 200. A 200 acknowledges a shop/redact you didn’t actually
perform, and Shopify retries for 48 hours anyway.

Your finding about the stale-token timing is a good one and I’d
report it. My own token expiry sat unnoticed for two days because
the refresh path had literally never executed in production - the
expiry timestamp not moving was the only evidence.

Used the official React Router starter template and ran into the same issue. Any updates on this, @Alan_G?

Update: For now, I’m using a temporary helper/workaround to handle the issue until the @shopify/shopify-app-react-router package receives an update.

import crypto from "node:crypto";
import { authenticate } from "~/shopify.server";

type WebhookContext = Awaited<ReturnType<typeof authenticate.webhook>>;

export type SafeWebhookContext = {
  shop: string;
  topic: string;
  session: WebhookContext["session"];
};

export async function authenticateWebhookSafely(
  request: Request,
): Promise<SafeWebhookContext> {
  const fallback = request.clone();

  try {
    return await authenticate.webhook(request);
  } catch (error) {
    if (!(error instanceof Response) || error.status !== 500) throw error;

    const rawBody = await fallback.text();

    if (!hasValidHmac(fallback, rawBody)) {
      throw new Response(undefined, {
        status: 401,
        statusText: "Unauthorized",
      });
    }

    const headerShop = fallback.headers.get("X-Shopify-Shop-Domain");
    const topicHeader = fallback.headers.get("X-Shopify-Topic");

    if (!headerShop || !topicHeader) throw error;

    let payloadShop: string | undefined;

    try {
      const payload = JSON.parse(rawBody) as Record<string, unknown>;

      payloadShop = [payload.shop_domain, payload.myshopify_domain].find(
        (v): v is string =>
          typeof v === "string" && v.endsWith(".myshopify.com"),
      );
    } catch {}

    if (payloadShop && payloadShop !== headerShop) {
      console.warn(
        `[webhook] shop header (${headerShop}) does not match signed payload (${payloadShop}); rejecting`,
      );

      throw new Response(undefined, {
        status: 401,
        statusText: "Unauthorized",
      });
    }

    const shop = payloadShop ?? headerShop;

    console.warn(
      `[webhook] token refresh failed for ${shop}; handling ${topicHeader} without a session`,
    );

    return {
      shop,
      topic: topicHeader.toUpperCase().replace(/\//g, "_"),
      session: undefined,
    };
  }
}

function hasValidHmac(request: Request, rawBody: string): boolean {
  const provided = request.headers.get("X-Shopify-Hmac-Sha256");
  const secret = process.env.SHOPIFY_API_SECRET;

  if (!provided || !secret) return false;

  const expected = crypto
    .createHmac("sha256", secret)
    .update(rawBody, "utf8")
    .digest("base64");

  const a = Buffer.from(provided);
  const b = Buffer.from(expected);

  return a.length === b.length && crypto.timingSafeEqual(a, b);
}```

Hey @webx47 - thanks for the bump and for sharing that helper.

Just confirming, this does look like a possible issue in @shopify/shopify-app-react-router and @shopify/shopify-app-remix libraries (not the template). authenticate.webhook() tries to refresh an expired offline token before your handler runs, and for an uninstalled shop that refresh can never succeed, so it 500s instead of continuing with session: undefined like the docs describe. It has been reported in shopify-app-js#3360 and there’s a community PR in progress. I can’t guarantee a turnaround time, but this is being tracked using the right methods there.

In the meantime your workaround is the right approach - the 500 is thrown after HMAC validation passes, so re-verifying the HMAC yourself and reading shop/topic from the headers is safe. That should unblock app review since the compliance webhooks will return a 2xx.

Let me know if I can help out further, hope this helps!