Skip to content
Ahmad Raza
Menu
All posts

9 min read

Migrating Your Shopify App to Expiring Offline Access Tokens

Shopify offline tokens that never expire are going away for public apps. Here is what changes, who must migrate, and a practical backend path: storage, OAuth, refresh-on-401, per-shop locks, and token exchange.

Migrating Your Shopify App to Expiring Offline Access Tokens
On this page

For years, a Shopify offline access token behaved like a password that never changed. You got it once during installation, saved it, and used it forever. That is changing. Shopify is moving apps to expiring offline access tokens: an access token that lasts about an hour, plus a refresh token you use to get a new one.

This guide covers what changed, whether you need to act, and how to migrate a backend step by step. It includes edge cases that show up in real migrations. Code samples are Java/Spring, but the approach works in any language.

What changed?

Before (non-expiring) After (expiring)
Access token lifetime Forever (until uninstall) About 1 hour (expires_in ≈ 3600)
Refresh token None About 90 days (refresh_token_expires_in ≈ 7776000)
What you store access_token access_token, refresh_token, and both expiry times
When the token stops working Practically never Every hour, so your app must renew it

Example response shape from a test store:

{
  "access_token": "shpat_xxx",
  "scope": "read_products,write_orders",
  "expires_in": 3599,
  "refresh_token": "shprt_xxx",
  "refresh_token_expires_in": 7775999
}

Refresh tokens rotate. Each refresh returns a new access token and a new refresh token. Always save both. If you keep using the old refresh token, it will eventually be rejected.

Do you need to migrate?

Public apps (listed on the App Store or distributed publicly): yes. Shopify's timeline:

  • January 1, 2027: public apps still using non-expiring offline tokens are delisted from the App Store and blocked from new installs. Existing installs keep working.
  • January 15, 2027: merchants using the app see a warning in the Shopify admin.
  • April 1, 2027: Shopify rejects GraphQL Admin API requests that use a non-expiring offline token. Merchants lose access to the app until they re-authenticate.

Custom apps and merchant-created apps: not required. Shopify's docs state that none of this timeline applies to custom apps or apps created by merchants. Custom apps can still opt in. Short-lived tokens limit damage if one leaks, and you will not have to rush if the policy expands later.

Always check the official page for the latest dates: Migrate to expiring offline access tokens.

Test it by hand first (Postman / curl)

Before you change any code, confirm the flow works with your app's client ID and secret.

Start the install / authorize flow

Open this in a browser (the URL must be on one line):

https://{shop}.myshopify.com/admin/oauth/authorize?client_id={client_id}&scope=read_products,write_orders&redirect_uri={url_encoded_redirect_uri}&state={random_nonce}

After you approve, Shopify redirects to your redirect_uri with ?code=.... Copy the code. It is single-use and short-lived.

Exchange the code for an expiring token

The only new parameter is expiring=1:

curl -X POST "https://{shop}.myshopify.com/admin/oauth/access_token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id={client_id}" \
  -d "client_secret={client_secret}" \
  -d "code={code}" \
  -d "expiring=1"

You should get expires_in and refresh_token in the response. If you do not, the parameter did not reach Shopify.

Call the Admin API with it

curl -X POST "https://{shop}.myshopify.com/admin/api/2025-04/graphql.json" \
  -H "Content-Type: application/json" \
  -H "X-Shopify-Access-Token: {access_token}" \
  -d '{"query":"{ shop { name } }"}'

Refresh it

curl -X POST "https://{shop}.myshopify.com/admin/oauth/access_token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=refresh_token" \
  -d "client_id={client_id}" \
  -d "client_secret={client_secret}" \
  -d "refresh_token={refresh_token}"

Check that the response contains a different access_token and a different refresh_token. If all four steps work, you are ready to change the code.

Implementation, step by step

Step 1: Extend your token storage

Store four values per shop instead of one:

public class ShopifyConfig {
    private String accessToken;
    private String refreshToken;          // new
    private Instant accessTokenExpiresAt; // new
    private Instant refreshTokenExpiresAt;// new
    // apiKey (client_id), secretKey (client_secret), ...
}

Store the expiry times as absolute timestamps (issuedAt + expires_in), not raw seconds. Capture issuedAt before the HTTP call so clock drift can only make the expiry slightly early, never late.

Map the response with explicit snake_case names:

public record ShopifyAccessTokenResponse(
        @JsonProperty("access_token") String accessToken,
        @JsonProperty("scope") String scope,
        @JsonProperty("expires_in") Long expiresIn,
        @JsonProperty("refresh_token") String refreshToken,
        @JsonProperty("refresh_token_expires_in") Long refreshTokenExpiresIn) { }

Step 2: Request expiring tokens in your OAuth callback

In the endpoint that exchanges code for a token, add expiring=1 and save every field:

MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
form.add("client_id", clientId);
form.add("client_secret", clientSecret);
form.add("code", code);
form.add("expiring", "1");
 
Instant issuedAt = Instant.now();
ShopifyAccessTokenResponse response =
        client.post("/admin/oauth/access_token", form, ShopifyAccessTokenResponse.class);
 
applyTokenResponse(shopifyConfig, response, issuedAt);
save(shopifyConfig);
static void applyTokenResponse(ShopifyConfig cfg, ShopifyAccessTokenResponse r, Instant issuedAt) {
    cfg.setAccessToken(r.accessToken());
    cfg.setRefreshToken(r.refreshToken());
    cfg.setAccessTokenExpiresAt(r.expiresIn() != null ? issuedAt.plusSeconds(r.expiresIn()) : null);
    cfg.setRefreshTokenExpiresAt(r.refreshTokenExpiresIn() != null
            ? issuedAt.plusSeconds(r.refreshTokenExpiresIn()) : null);
}

Usually no frontend change is needed. The frontend just sends the merchant to Shopify and forwards the code to your backend.

Step 3: Choose a renewal strategy

There are two common approaches:

  1. Proactive: before each call, check accessTokenExpiresAt and refresh if it is within about 60 seconds of expiring.
  2. Reactive (retry on 401): make the call. If Shopify returns 401 Unauthorized, refresh the token and retry once.

The reactive approach keeps the happy path fast:

Token valid:    call Shopify → success → done
Token expired:  call Shopify → 401 → refresh token → call Shopify again → done

It also covers cases the proactive path misses, such as a token revoked or replaced before its expiry time. You can combine both if you want.

Step 4: Wrap every Admin API call in a single helper

Do not scatter refresh logic across the codebase. Put it in one place:

public <T> T executeWithTokenRefresh(PlatformConfig config,
                                     Supplier<T> action,
                                     Runnable onTokenRefreshed) {
    String usedToken = config.getShopifyConfig().getAccessToken();
 
    // Never call Shopify with an empty token; it can only fail.
    if (!StringUtils.hasText(usedToken)) {
        if (!refreshAccessToken(config, usedToken)) {
            throw new ShopifyReauthorizationRequiredException(config.getUuid());
        }
        onTokenRefreshed.run();
        return action.get();
    }
 
    try {
        return action.get();
    } catch (HttpClientErrorException ex) {
        if (ex.getStatusCode().value() != 401) throw ex;          // only handle 401
        if (!refreshAccessToken(config, usedToken)) throw ex;     // can't renew: surface the original error
        onTokenRefreshed.run();                                   // rebuild clients holding the old token
        return action.get();                                      // retry exactly once
    }
}

Route every GraphQL or REST call through it:

private String queryAdmin(String query, Object variables) {
    return tokenService.executeWithTokenRefresh(platformConfig,
            () -> graphQLClient.query(query, variables),
            () -> initGraphQLClient(platformConfig)); // client must pick up the new token
}

Two details matter:

  • The action must read the token each time it runs. If your HTTP client copied the token into a header when it was built, the retry will send the old token again. That is what the onTokenRefreshed hook is for: rebuild the client.
  • Retry only once. If the second call also returns 401, something else is wrong (uninstalled app, revoked scope). Looping will not fix it.

Step 5: Refresh safely (concurrency is the hard part)

Refresh tokens rotate, so two requests refreshing at the same time can break each other. Request A refreshes and gets refresh token R2. Request B then refreshes with the old R1 and overwrites the stored token with its own result. Depending on timing, a store can end up holding a token another worker has already replaced. Shopify's docs say directly: refresh one store at a time.

Example refresh routine:

public boolean refreshAccessToken(PlatformConfig config, String rejectedToken) {
    String lockKey = "shopify-token-refresh:" + config.getUuid();
    String lock;
    try {
        lock = lockManager.acquireLock(lockKey);             // distributed lock (e.g. Redis)
    } catch (LockException e) {
        return awaitConcurrentRefresh(config, rejectedToken); // someone else is refreshing; poll the DB
    }
    try {
        ShopifyConfig stored = loadFromDatabase(config.getUuid()); // NOT from cache
 
        // 1. Another request already renewed it? Use that token, don't refresh again.
        if (hasText(stored.getAccessToken()) && !stored.getAccessToken().equals(rejectedToken)) {
            copyTokens(stored, config.getShopifyConfig());
            return true;
        }
        // 2. Nothing to refresh with (legacy non-expiring token, or never authorized).
        if (!hasText(stored.getRefreshToken())) return false;
 
        // 3. Refresh.
        Instant issuedAt = Instant.now();
        ShopifyAccessTokenResponse r = postRefresh(config.getStoreUrl(), stored);
        ShopifyConfig renewed = new ShopifyConfig();
        applyTokenResponse(renewed, r, issuedAt);
        if (!hasText(renewed.getRefreshToken())) {           // defensive: never lose the refresh token
            renewed.setRefreshToken(stored.getRefreshToken());
            renewed.setRefreshTokenExpiresAt(stored.getRefreshTokenExpiresAt());
        }
        updateTokensOnly(config.getUuid(), renewed);         // targeted $set, then evict caches
        copyTokens(renewed, config.getShopifyConfig());
        return true;
    } catch (HttpClientErrorException e) {
        log.error("Refresh rejected; merchant must re-authorize. shop={}", config.getUuid());
        return false;
    } finally {
        lockManager.releaseLock(lockKey, lock);
    }
}

What each piece protects against:

Technique Prevents
Per-shop distributed lock Two workers refreshing with the same refresh token
Re-read tokens from the database inside the lock Refreshing again after another worker already did
Compare the stored token with the rejected token Spending a rotation when a fresh token is already saved
Waiting callers poll the DB instead of failing Failed requests during a burst of traffic
Targeted update of only the 4 token fields A full-document save elsewhere overwriting new tokens with old ones
Evict caches after writing Other instances keeping the expired token in memory
HTTP timeouts on the refresh call A hung refresh holding the lock

A trap worth calling out: if another part of your app loads the whole shop config, edits an unrelated field, and saves the whole document, it can silently restore an old token. Either update tokens with targeted field updates only, or merge on save and keep whichever token set has the later accessTokenExpiresAt. Doing both is safer.

Step 6: Handle "can't refresh" cleanly

Refresh can fail for good if:

  • the refresh token has expired (unused for about 90 days)
  • the app was uninstalled or its credentials were rotated
  • the shop still has an old non-expiring token and therefore no refresh token
  • the token fields are empty (manual DB edits, or a broken install)

Shopify's refresh endpoint returns 401 with {"error": "invalid_request"} in these cases. Do not retry. Instead:

  • Rethrow the original 401, or throw a clear error like ShopifyReauthorizationRequiredException.
  • Log it in a way that alerts can catch.
  • Ask the merchant to re-open or re-authorize the app. That runs the OAuth flow again and issues a new token pair.

Network errors, timeouts, 5xx and 429 from the refresh endpoint are temporary, and Shopify says it is safe to retry them with the same refresh token.

Shops that installed before your change still have a non-expiring token. You have two options.

Option A: re-authorize. The merchant re-opens the app, and your updated OAuth callback stores an expiring pair.

Option B: exchange the old token on the server, with no merchant action:

curl -X POST "https://{shop}.myshopify.com/admin/oauth/access_token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
  -d "client_id={client_id}" \
  -d "client_secret={client_secret}" \
  -d "subject_token={existing_non_expiring_token}" \
  -d "subject_token_type=urn:shopify:params:oauth:token-type:offline-access-token" \
  -d "requested_token_type=urn:shopify:params:oauth:token-type:offline-access-token" \
  -d "expiring=1"

Things to know about Option B:

  • The old token is permanently invalidated for GraphQL Admin API requests once the exchange succeeds. Save the new pair before you do anything else.
  • If you lose the response, you can repeat the same request within 7 days to get the same token pair back.
  • Run it as a one-time batch job, one shop at a time, using the same per-shop lock as your refresh logic.

Step 8: Do not forget idle shops

With the reactive approach, a token is only refreshed when the shop makes a call. If a shop makes no calls for about 90 days, its refresh token expires and the merchant has to re-authorize. If that matters to you, add a scheduled job that refreshes any shop whose refreshTokenExpiresAt is within the next few weeks.

Security checklist

  • Do not log client_secret, access_token or refresh_token. HTTP clients often log form bodies; add these fields to your masking list.
  • Keep refresh tokens on the server. Never send them to the browser.
  • Verify the HMAC on the OAuth callback, and use a cryptographically random state nonce (not Math.random()).
  • URL-encode scope and redirect_uri when building the authorize URL.
  • Rotating your client secret invalidates tokens tied to the old secret, and every shop must be re-authorized or re-migrated.

How to test your implementation

Automated tests worth writing:

  1. Valid token: the action runs once, with no refresh call.
  2. Expired token: 401, one refresh, the new token is saved, and the action is retried with the new token.
  3. No refresh token: the original 401 is rethrown and nothing is saved.
  4. Concurrent renewal: another request already saved a new token, so the retry uses it without calling Shopify.
  5. Refresh rejected by Shopify: the original 401 is rethrown and the lock is released.
  6. Non-401 error (e.g. 500): rethrown as-is, with no refresh.
  7. Blank access token + valid refresh token: refresh happens before calling Shopify.
  8. Blank access token + blank refresh token: fails fast and Shopify is never called.

A lightweight local HTTP server works well as a fake token endpoint, so you can check the exact form fields sent (grant_type=refresh_token, refresh_token=...).

Manual tests against a dev store:

  • Install the app and confirm the DB has refresh_token and both expiry timestamps.
  • Wait an hour (or change the stored access token to a dummy value) and trigger an API call. In the logs you should see a 401, then a refresh, then a successful retry.
  • Clear the token fields, trigger a call, and confirm Shopify is not called and you get a clear "re-authorize" error.

Summary

  1. Add expiring=1 to the code-for-token exchange.
  2. Store the access token, refresh token, and both expiry times.
  3. Route every Admin API call through one helper that refreshes on 401 and retries once.
  4. Refresh under a per-shop lock, re-read from the database first, and always save the rotated refresh token.
  5. Update only the token fields and evict caches, so stale writes cannot restore old tokens.
  6. When refresh is impossible, fail clearly and ask the merchant to re-authorize.
  7. Migrate existing non-expiring tokens, and keep idle shops' refresh tokens alive.

None of these steps is large, but they all need to be in place. With them, your app keeps working whether the token is an hour old or a minute old.

Building Shopify apps, checkout, or storefront integrations and want a second pair of eyes on the migration? Book a 30-min call or email ahmadraza365pro@gmail.com.

References

  • 5 min read

    A 30-Day Agentic Commerce Rollout for a Next.js Store

    A practical, week by week plan to make a Next.js store ready for AI shopping agents: clean the data, ship a read only catalog MCP server, add carts, hand off to confirmed checkout, then log and cap everything.

  • 5 min read

    Fraud and Abuse When Agents Shop Your Checkout

    AI shopping agents look a lot like bots, and bots look a lot like agents. Here is how to tell them apart, where to put bot challenges, and why hosted checkout like Shop Pay is your best trust boundary.

  • 4 min read

    Hydrogen SDK vs Calling Storefront API Yourself in 2026

    Shopify's Hydrogen SDK now reaches beyond Remix and React Router into other frameworks. Here is what it gives you for agent ready storefronts, what a thin Next.js client gives you, and when each one pays off.