Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 55 ยท Authentication and Sessions

Token Exchange and Access Tokens

Learn how Shopify token exchange swaps a session token for an online or offline access token, how expiring tokens work, and how to store and reuse tokens safely.

A session token (see Session Tokens for Embedded Apps) answers one question: who is calling my server? It lives for about a minute and cannot talk to Shopify's APIs. To read products or update inventory you need an access token, a longer-lived credential that you send to the Admin API in the X-Shopify-Access-Token header.

For embedded apps with managed installation, you get that access token by token exchange: your server sends the session token to Shopify, and Shopify answers with an access token for the scopes the merchant already granted (see Managed Installation and Access Scopes). There is no redirect, no consent screen and no authorization code. This lesson shows the request, the two kinds of tokens you can ask for, how expiry changes your design, and how to store tokens.

Requests to Shopify cannot run on this site, so the real HTTP calls are read-only. The runnable examples are stand-ins: a pretend Shopify endpoint and a token store written in plain JavaScript. Field names follow Shopify's documented token exchange grant; check the current documentation for any newer options before you ship.

The idea in one picture

sequenceDiagram
  participant B as Embedded UI
  participant S as Your server
  participant H as Shopify (shop domain)
  B->>S: Request with session token
  S->>S: Verify session token
  S->>S: Look up stored access token for this shop
  alt Token missing or expired
    S->>H: POST /admin/oauth/access_token (token exchange)
    H-->>S: Access token (+ expiry for online tokens)
    S->>S: Store the token
  end
  S->>H: Admin API call with X-Shopify-Access-Token
  H-->>S: Data
  S-->>B: Response

Exchange only when you have no usable token; otherwise reuse the stored one.

The exchange request

You send a POST to the shop's own admin domain with these fields:

HTTP
POST https://example-store.myshopify.com/admin/oauth/access_token
Content-Type: application/json
Accept: application/json

{
  "client_id": "<your client id>",
  "client_secret": "<your client secret>",
  "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
  "subject_token": "<the verified session token>",
  "subject_token_type": "urn:ietf:params:oauth:token-type:id_token",
  "requested_token_type": "urn:shopify:params:oauth:token-type:offline-access-token"
}

The long urn: strings come from the OAuth 2.0 Token Exchange standard (RFC 8693). They look odd, but they are constants:

  • grant_type says "this is a token exchange".
  • subject_token is the session token (a JWT, which OAuth calls an id token here) and subject_token_type names that format.
  • requested_token_type picks the kind of token you want back: urn:shopify:params:oauth:token-type:offline-access-token or urn:shopify:params:oauth:token-type:online-access-token. The next lessons explain the difference in depth (Online vs Offline Tokens).

Shopify validates the session token itself, checks that it belongs to your app and the shop, and answers with JSON that contains at least access_token and scope. Online tokens also report their lifetime and the staff user they belong to.

The request carries your client secret. Make it only from your server, never from the browser, and never log the request body.

In the official React Router app template you almost never write this request. authenticate.admin(request) verifies the session token, checks for a stored session and performs the exchange when needed. Knowing the mechanics helps when you debug a failed exchange or build a backend without the template.

Two kinds of token, one request

  • An offline token belongs to the shop. It is for work that happens with nobody looking at the screen: webhooks, background jobs, scheduled syncs.
  • An online token belongs to one staff user. It carries that user's permissions and expires after a limited time (24 hours is documented for online tokens).

A common pattern is to request an offline token the first time a shop uses the app and keep it, and to request online tokens only for features that must respect the logged-in user's permissions.

Expiring tokens

Historically an offline token never expired; you stored it once and used it forever. That is convenient but dangerous, because a leaked token stays valid until the merchant uninstalls the app. Shopify has been moving toward expiring offline tokens, which come with a refresh token. Your code uses the access token until it expires and then trades the refresh token for a new pair.

The consequences for your design are the same whichever lifetime a token has:

  1. Store the expiry next to the token.
  2. Check it before use, with a small safety margin, so you never send a token that dies mid-flight.
  3. Replace, don't append. When you refresh or re-exchange, overwrite the stored record. With refresh tokens, store the new refresh token too, because the old one is typically single-use.
  4. Handle a 401 from Shopify by exchanging again, once, then giving up with a clear error.

Because details such as lifetimes and opt-in flags change, treat the exact numbers as something to read from the current documentation, not to hard-code from a tutorial.

Storing tokens safely

An access token is a password for a merchant's store. Treat it like one:

  • Keep it in your database, keyed by shop domain (plus user id for online tokens). The template stores sessions with Prisma; see Databases and Session Storage in Production.
  • Encrypt tokens at rest if your database or backups might be exposed to people who should not see them.
  • Never send a token to the browser. The browser holds a session token only; your server holds access tokens.
  • Delete the stored tokens when the app is uninstalled (the app/uninstalled webhook tells you), and again when a shop-redact request arrives; see Privacy, GDPR and Mandatory Webhooks.

A stand-in Shopify exchange endpoint

The first runnable example plays both sides. A function fakeShopify stands in for the endpoint: it checks the grant fields and the session token, then returns a token. Everything is deterministic and no network is used.

Node.js Token exchange against a pretend Shopify

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.

Notice that the exchange fails if the session token is expired or unknown. That is why the order matters: you must verify and then use the session token promptly; it is not something you can store and replay later.

A token store that exchanges only when needed

The second stand-in is the part you would really write: a store that keeps one token per shop (offline) and one per shop-and-user (online), reuses it while valid, and exchanges again when it is missing or about to expire. It counts how many exchanges were needed.

Node.js A token store that reuses and refreshes

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.

Six lookups caused only four exchanges. Step 2 and 4 reuse cached tokens. Step 5 is a different user, so it needs its own online token. Step 6 asks for user 42's token only 30 seconds before it expires, which is inside the 60-second margin, so the store exchanges early instead of sending a token that might expire on the way. Finally, uninstalling deletes every record for the shop.

What can go wrong

  • Expired or replayed session tokens. Exchange immediately after verification; session tokens last about a minute.
  • Wrong requested type. Asking for an online token and then using it in a webhook handler fails, because there is no logged-in user. See the next lesson.
  • Scope drift. If the merchant later approves new scopes, an old stored token may not include them. Re-exchange to get a token that matches the current grant.
  • Stale tokens after reinstall. A reinstall can invalidate older tokens. If Shopify returns 401, drop the stored token and exchange once more.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does token exchange take as input, and what does it return?

    You send the session token as the subject token together with your client id and secret, and Shopify returns an access token for the scopes the merchant already granted.
  2. 2. Where must the token exchange request be made from?

    The client secret must never reach the browser. Exchange from your server and keep access tokens there too.
  3. 3. Your stored online token expires in 30 seconds. What should a careful token store do?

    A margin avoids sending a token that expires while the request is in flight. Replace the stored record with the fresh token.
  4. 4. When should you delete a shop's stored tokens?

    After uninstall the tokens are useless and a liability. Delete them when you receive the uninstall webhook and make sure shop redaction removes any remainder.

Summary

  • A session token authenticates the request to your server; an access token authenticates your server to Shopify's APIs.
  • Token exchange swaps a verified session token for an access token with one server-side POST, using constant urn: identifiers for the grant and token types.
  • You choose offline (shop-bound, for background work) or online (user-bound, expiring) in requested_token_type.
  • Store expiry with each token, use a safety margin, replace records on refresh and re-exchange once on a 401.
  • Keep access tokens only on the server, encrypt them at rest where appropriate and delete them on uninstall.

Next: Online vs Offline Tokens helps you choose the right kind for each job.