Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/theme-dev-keep-session-cookie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/theme': patch
---

Fix `theme dev` switching to the live theme ("Theme ID mismatch", `null` sections) after Storefront API, cart, checkout, or account requests
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,62 @@ describe('dev proxy', () => {
})
})

describe('proxyStorefrontRequest — dev session cookie', () => {
const responseSettingEssential = () =>
new Response('OK', {
headers: [
['set-cookie', '_shopify_essential=:ROTATED:; path=/; secure; HttpOnly; SameSite=Lax'],
['set-cookie', 'cart_currency=USD; path=/; SameSite=Lax'],
],
})

const createSessionCtx = () =>
({
...ctx,
type: 'theme',
session: {
storeFqdn: 'my-store.myshopify.com',
sessionCookies: {_shopify_essential: ':DEV-THEME-BOUND:'},
storefrontToken: 'sfr-devtools-token',
},
}) as unknown as DevServerContext

beforeEach(() => {
vi.stubGlobal(
'fetch',
vi.fn().mockImplementation(async () => responseSettingEssential()),
)
})

afterEach(() => {
vi.unstubAllGlobals()
})

test.each([
['GET', '/cart.js'],
['POST', '/cart/add.js'],
['POST', '/cart/change.js?sections=cart-drawer'],
['GET', '/cart'],
['GET', '/checkouts/xyz'],
['GET', '/account/logout'],
['POST', '/api/2025-01/graphql.json'],
])('keeps the dev session cookie when %s %s rotates _shopify_essential', async (method, path) => {
const sessionCtx = createSessionCtx()
const response = await proxyStorefrontRequest(createH3Event(method, path), sessionCtx)

expect(sessionCtx.session.sessionCookies).toHaveProperty('_shopify_essential', ':DEV-THEME-BOUND:')
// The browser still receives the cookie for its own jar:
expect(response.headers.getSetCookie().join(',')).toContain('_shopify_essential=:ROTATED:')
})

test('stores _shopify_essential from requests sent with the dev session', async () => {
const sessionCtx = createSessionCtx()
await proxyStorefrontRequest(createH3Event('GET', '/products/some-product.js'), sessionCtx)

expect(sessionCtx.session.sessionCookies).toHaveProperty('_shopify_essential', ':ROTATED:')
})
})

describe('proxyStorefrontRequest — Storefront API passthrough', () => {
const passthroughCtx = {
...ctx,
Expand Down
13 changes: 11 additions & 2 deletions packages/theme/src/cli/utilities/theme-environment/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,11 @@ interface PatchResponseOptions {
* Only the storefront exit page needs this: it redirects shoppers to another site.
*/
keepExternalRedirects?: boolean
/**
* Store the response's `_shopify_essential` as the dev session cookie (default: true).
* Only requests sent with the dev session's credentials get a cookie bound to the development theme.
*/
captureSessionCookie?: boolean
}

function patchProxiedResponseHeaders(ctx: DevServerContext, rawResponse: Response, options?: PatchResponseOptions) {
Expand Down Expand Up @@ -301,7 +306,7 @@ function patchProxiedResponseHeaders(ctx: DevServerContext, rawResponse: Respons
response.headers.set('Set-Cookie', patchCookieDomains(setCookieHeader, ctx).join(','))

const latestShopifyEssential = setCookieHeader.join(',').match(SESSION_COOKIE_REGEXP)?.[1]
if (latestShopifyEssential) {
if (latestShopifyEssential && options?.captureSessionCookie !== false) {
ctx.session.sessionCookies[SESSION_COOKIE_NAME] = latestShopifyEssential
}
}
Expand Down Expand Up @@ -407,7 +412,11 @@ export function proxyStorefrontRequest(event: H3Event, ctx: DevServerContext): P
redirect: 'manual',
headers,
} as RequestInit & {duplex?: 'half'})
.then((response) => patchProxiedResponseHeaders(ctx, response))
.then((response) =>
patchProxiedResponseHeaders(ctx, response, {
captureSessionCookie: !isPassthroughRequest(event) && needsBearerToken(event.path),
}),
)
.catch((error: Error) => {
throw createFetchError(recordError(error), url)
})
Expand Down
Loading