Skip to content

Commit 64fbcb6

Browse files
authored
Make instant() resilient to a leaked navigation-testing cookie (#95375)
The Instant Navigation Testing helper threw `An instant() scope is already active` whenever it found the `next-instant-navigation-testing` cookie set at acquire time. Because Playwright reuses one browser context across every test in a file, a cookie left behind by an earlier scope poisoned the shared jar and made every following `instant()` call fail fast, cascading through the suite. The cookie can outlive its scope: under the lock, each MPA page load asynchronously re-writes it via `cookieStore`, and that write can land right after the scope's release deletes it but before the client observes the deletion, resurrecting a captured-state entry that the change handler then ignores. Nesting is now tracked in-process, keyed on the browser context, rather than inferred from cookie presence. The context is the right granularity because the instant cookie is context-scoped: concurrent scopes on the same context share one cookie and conflict, while scopes on separate contexts or browsers are independent and must both run. On acquire we clear any stale cookie instead of throwing, and the release re-reads and re-deletes until the cookie stays gone, defeating the resurrection race. New tests cover recovery from a leaked cookie and concurrent scopes across separate contexts. --- <sub>Stack created with <a href="GitHub">https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a href="Give" rel="nofollow">https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
1 parent a26a1d6 commit 64fbcb6

2 files changed

Lines changed: 172 additions & 51 deletions

File tree

‎packages/next-playwright/src/index.ts‎

Lines changed: 96 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,23 @@ interface PlaywrightPage {
2929

3030
const INSTANT_COOKIE = 'next-instant-navigation-testing'
3131

32+
// Browser contexts that currently have an instant() scope executing. The
33+
// instant cookie is scoped to the browser context, so the context is the
34+
// natural granularity for the scope: two concurrent instant() calls on the same
35+
// context share one cookie and genuinely conflict, whereas calls on different
36+
// contexts (or different browsers) are independent and must not. Keying on the
37+
// context object preserves that isolation while giving a race-free nesting
38+
// signal.
39+
//
40+
// We track this in-process rather than inferring nesting from the cookie's
41+
// presence: a locked page asynchronously re-writes the instant cookie on every
42+
// MPA load (see navigation-testing-lock.ts), and that write can land right
43+
// after a prior scope's release deletes it, resurrecting the cookie once the
44+
// scope has already ended. Treating such a leftover as an active scope would
45+
// turn a benign residue into a cascading failure across every later test that
46+
// shares the browser context.
47+
const contextsWithActiveScope = new WeakSet<PlaywrightBrowserContext>()
48+
3249
/**
3350
* Runs a function with instant navigation enabled. Within this scope,
3451
* navigations render the prefetched UI immediately and wait for the
@@ -55,67 +72,95 @@ export async function instant<T>(
5572
fn: () => Promise<T>,
5673
options?: { baseURL?: string }
5774
): Promise<T> {
58-
// Check for nested instant() calls. The cookie is scoped to the browser
59-
// context, so we can detect nesting by checking if it's already set.
60-
const existingCookies = await page.context().cookies()
61-
if (existingCookies.some((c) => c.name === INSTANT_COOKIE)) {
75+
const context = page.context()
76+
if (contextsWithActiveScope.has(context)) {
6277
throw new Error(
6378
'An instant() scope is already active. Nesting instant() ' +
6479
'calls is not supported. Did you forget to await the ' +
6580
'previous instant() call?'
6681
)
6782
}
6883

69-
// Acquire the lock by setting the cookie via the browser context. This
70-
// ensures the cookie is present even on the very first navigation.
71-
// The cookie triggers the CookieStore change event in
72-
// navigation-testing-lock.ts, which acquires the in-memory navigation lock.
84+
// Resolve the cookie's scope before touching any browser state, so misuse on
85+
// a fresh page (no baseURL and no prior navigation) fails with the
86+
// descriptive error from resolveURL rather than half-entering a scope.
7387
const { hostname } = new URL(resolveURL(page, options))
74-
await step('Acquire Instant Lock', () =>
75-
page.context().addCookies([
76-
{
77-
name: INSTANT_COOKIE,
78-
value: JSON.stringify([0, `p${Math.random()}`]),
79-
domain: hostname,
80-
path: '/',
81-
},
82-
])
83-
)
88+
89+
contextsWithActiveScope.add(context)
8490
try {
85-
return await fn()
91+
// A completed prior scope on this context can leave the cookie behind (its
92+
// client-side release races an in-flight captured-cookie write from a
93+
// locked MPA page load; see the note above). No scope is active for this
94+
// context, so a present cookie is always stale here — clear it before
95+
// acquiring so a completed prior scope never blocks this one.
96+
await releaseInstantCookie(context)
97+
98+
// Acquire the lock by setting the cookie via the browser context. This
99+
// ensures the cookie is present even on the very first navigation. The
100+
// cookie triggers the CookieStore change event in
101+
// navigation-testing-lock.ts, which acquires the in-memory navigation lock.
102+
await step('Acquire Instant Lock', () =>
103+
context.addCookies([
104+
{
105+
name: INSTANT_COOKIE,
106+
value: JSON.stringify([0, `p${Math.random()}`]),
107+
domain: hostname,
108+
path: '/',
109+
},
110+
])
111+
)
112+
try {
113+
return await fn()
114+
} finally {
115+
await step('Release Instant Lock', () => releaseInstantCookie(context))
116+
}
86117
} finally {
87-
// Release the lock by expiring the instant cookie, leaving every other
88-
// cookie untouched.
89-
//
90-
// We must NOT use `context.clearCookies({ name: INSTANT_COOKIE })` here.
91-
// Playwright implements a filtered `clearCookies` by clearing the ENTIRE
92-
// cookie jar and then re-adding the cookies that don't match the filter.
93-
// That briefly removes the application's own cookies too. Next.js reacts
94-
// to the instant cookie's deletion by immediately re-rendering, and if
95-
// that render's request races the empty window it observes none of the
96-
// app's cookies (e.g. a navigated page renders as if no cookies were set).
97-
//
98-
// Instead we read the instant cookie's stored entries (Next.js may have
99-
// updated the value, e.g. from [0] to [1,null], but preserves the domain
100-
// and path) and re-add each with a past expiry, which deletes only those
101-
// entries without disturbing the rest of the jar.
102-
await step('Release Instant Lock', async () => {
103-
const instantCookies = (await page.context().cookies()).filter(
104-
(cookie) => cookie.name === INSTANT_COOKIE
105-
)
106-
if (instantCookies.length > 0) {
107-
await page.context().addCookies(
108-
instantCookies.map((cookie) => ({
109-
name: cookie.name,
110-
value: cookie.value,
111-
domain: cookie.domain,
112-
path: cookie.path,
113-
// A past expiry (Unix epoch seconds) deletes the cookie.
114-
expires: 1,
115-
}))
116-
)
117-
}
118-
})
118+
contextsWithActiveScope.delete(context)
119+
}
120+
}
121+
122+
/**
123+
* Deletes the instant cookie, leaving every other cookie untouched.
124+
*
125+
* We must NOT use `context.clearCookies({ name: INSTANT_COOKIE })` here.
126+
* Playwright implements a filtered `clearCookies` by clearing the ENTIRE cookie
127+
* jar and then re-adding the cookies that don't match the filter. That briefly
128+
* removes the application's own cookies too. Next.js reacts to the instant
129+
* cookie's deletion by immediately re-rendering, and if that render's request
130+
* races the empty window it observes none of the app's cookies (e.g. a
131+
* navigated page renders as if no cookies were set).
132+
*
133+
* Instead we read the instant cookie's stored entries (Next.js may have updated
134+
* the value, e.g. from [0] to [1,null], but preserves the domain and path) and
135+
* re-add each with a past expiry, which deletes only those entries without
136+
* disturbing the rest of the jar.
137+
*
138+
* A locked MPA page load can asynchronously re-write (resurrect) the cookie
139+
* just after we delete it: the client only stops writing once it observes the
140+
* deletion, an event that races the pending write. We therefore re-read and
141+
* re-delete until the cookie stays gone, bounded so a cookie that some other
142+
* actor keeps re-setting can't loop forever.
143+
*/
144+
async function releaseInstantCookie(
145+
context: PlaywrightBrowserContext
146+
): Promise<void> {
147+
for (let attempt = 0; attempt < 5; attempt++) {
148+
const instantCookies = (await context.cookies()).filter(
149+
(cookie) => cookie.name === INSTANT_COOKIE
150+
)
151+
if (instantCookies.length === 0) {
152+
return
153+
}
154+
await context.addCookies(
155+
instantCookies.map((cookie) => ({
156+
name: cookie.name,
157+
value: cookie.value,
158+
domain: cookie.domain,
159+
path: cookie.path,
160+
// A past expiry (Unix epoch seconds) deletes the cookie.
161+
expires: 1,
162+
}))
163+
)
119164
}
120165
}
121166

‎test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,82 @@ describe('instant-navigation-testing-api', () => {
216216
})
217217
})
218218

219+
it('recovers from a stale instant cookie left by a prior scope', async () => {
220+
const page = await openPage(next, '/')
221+
222+
// Simulate a cookie leaked by a previous instant() scope. A locked MPA page
223+
// load re-writes the cookie asynchronously and can resurrect it right after
224+
// a prior scope's release deletes it, leaving a captured-state entry in the
225+
// shared browser context. Because the context is reused across tests, a new
226+
// instant() call must treat that residue as stale (clearing it) rather than
227+
// reporting an active scope, or every following test would cascade-fail.
228+
const { hostname } = new URL(next.url)
229+
await page.context().addCookies([
230+
{
231+
name: 'next-instant-navigation-testing',
232+
value: JSON.stringify([1, 'c-stale', null]),
233+
domain: hostname,
234+
path: '/',
235+
},
236+
])
237+
238+
let ranCallback = false
239+
await instant(page, async () => {
240+
ranCallback = true
241+
await page.click('#link-to-target')
242+
const loadingShell = page.locator('[data-testid="loading-shell"]')
243+
await loadingShell.waitFor({ state: 'visible' })
244+
})
245+
expect(ranCallback).toBe(true)
246+
247+
// After exiting the scope the cookie is gone again, so a normal navigation
248+
// is not locked and dynamic content streams in.
249+
const dynamicContent = page.locator('[data-testid="dynamic-content"]')
250+
await dynamicContent.waitFor({ state: 'visible' })
251+
})
252+
253+
it('allows concurrent instant scopes across separate browser contexts', async () => {
254+
const page = await openPage(next, '/')
255+
256+
// A second, independent browser context. Its cookie jar and its page's
257+
// navigation lock are separate from the first context's, so a concurrent
258+
// instant() scope here must not be reported as already active against the
259+
// first. This guards against tracking the active scope per-process instead
260+
// of per-context.
261+
const browser = page.context().browser()
262+
if (!browser) {
263+
throw new Error('Expected the page context to expose a browser instance')
264+
}
265+
const otherContext = await browser.newContext()
266+
try {
267+
const otherPage = await otherContext.newPage()
268+
await otherPage.goto(next.url)
269+
270+
let ranFirst = false
271+
let ranSecond = false
272+
await Promise.all([
273+
instant(page, async () => {
274+
ranFirst = true
275+
await page.click('#link-to-target')
276+
await page
277+
.locator('[data-testid="loading-shell"]')
278+
.waitFor({ state: 'visible' })
279+
}),
280+
instant(otherPage, async () => {
281+
ranSecond = true
282+
await otherPage.click('#link-to-target')
283+
await otherPage
284+
.locator('[data-testid="loading-shell"]')
285+
.waitFor({ state: 'visible' })
286+
}),
287+
])
288+
expect(ranFirst).toBe(true)
289+
expect(ranSecond).toBe(true)
290+
} finally {
291+
await otherContext.close()
292+
}
293+
})
294+
219295
it('renders shell on page reload', async () => {
220296
const page = await openPage(next, '/target-page')
221297

0 commit comments

Comments
 (0)