Fetching Shopify orders from a Cloudflare Worker
A storefront page cannot call the Shopify Admin API directly. The access token would have to ship to the browser, and anyone could read it. A Cloudflare Worker fixes that: the browser talks to the Worker, and the Worker talks to Shopify. I built a small proof of concept this way against a development store. It is not a production system, and the example below is generic.
The query#
The Admin GraphQL API lets you ask for exactly the fields you need. For an order lookup, a short query is enough:
query OrdersByEmail($query: String!) {
orders(first: 5, query: $query) {
nodes {
id
name
createdAt
displayFulfillmentStatus
totalPriceSet {
shopMoney {
amount
currencyCode
}
}
}
}
}
The query variable uses Shopify’s search syntax, for example email:customer@example.com.
The Worker#
The Worker holds the token as a secret, sends the query and returns only what the page needs:
const ORDERS_QUERY = `...`; // the query above
export default {
async fetch(request, env) {
const { query } = await request.json();
const response = await fetch(
`https://${env.SHOP_DOMAIN}/admin/api/${env.API_VERSION}/graphql.json`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': env.ADMIN_TOKEN,
},
body: JSON.stringify({ query: ORDERS_QUERY, variables: { query } }),
},
);
const { data } = await response.json();
return Response.json(data.orders.nodes);
},
};
The shop domain, API version and token all come from env, so none of them are in the code.
What this version leaves out#
It does not check who is asking. It does not rate limit, cache or log. A real lookup must confirm the person owns the order before returning anything, for example by matching an order number and an email together. I would add those checks before this went anywhere near real customers. [TBD: list what the current proof of concept actually includes.]
Why a Worker#
The Worker is small, starts fast and needs no server of its own. For one endpoint that wraps one API call, that is a good fit. If the endpoint grows, I would revisit that choice.