Register the Playwright download event before triggering the export.
Use download.saveAs() to store the result in a worker-owned location before browser cleanup.
Treat a suggested filename as metadata. Choose your own destination and check the downloaded bytes.
Require a content, schema, or revision check before marking an export accepted.
Use the application's export status to reconcile a missing or interrupted file.
Test artifact transfer with your exact managed connection, then close the page and confirm session termination separately.
What happens when Playwright downloads a file from a remote browser?
A file download begins in the browser after a page action. Playwright exposes a download object that can report the source URL, proposed name, and transfer result. Your worker can save a supported download to an explicit path, then verify what actually arrived. Nstdata provides managed browser sessions for workflows that need to interact with applications and obtain outputs.
A useful example is an authorized staging inventory report. The team expects a CSV containing a known fixture SKU and quantity. A click on Export can succeed while the generated file contains only a header, stale data, or an error payload. Accept the result only after inspecting the saved content. The end-to-end browser QA guide separates an action's completion from a business assertion, which applies equally to files.
Which Playwright download fields should you use?
Use the download event to identify the artifact, failure() to check the transfer outcome, and saveAs() to export the file to a worker-owned path. Derive the expected artifact identity from the job, rather than accepting whichever attachment arrives first. The describes these methods and the remote-connection limitation of .
Watch for the expected download or application status
Download event
The browser noticed an attachment
Correlate it to the page, action and expected artifact
Suggested filename
The name proposed by the browser
Use a worker-owned safe path rather than concatenating it into a filesystem location
failure() returns null
The browser reports no transfer failure
Save the artifact and verify its contents
File saved
The worker received bytes
Check type, schema, source revision and required records
A Playwright download belongs to the browser context that produced it. The Playwright download guide notes that context cleanup removes temporary downloads. Save your copy before closing the page or context. In a managed runtime, verify how your provider and client deliver the artifact, especially when the browser and worker use separate filesystems.
How do you save and verify one inventory export?
Use the companion fixture to trigger one CSV export. Attach a browser, save to an isolated temporary folder, and compare the bytes with the expected record. The example runs on Node.js 22 with playwright-core@1.65.1. Install local Chromium with npx playwright-core install chromium and run node fixture.mjs to serve the approved loopback app.
Step 1. Specify the file acceptance rule
The test expects one header and a row for TEST-42. The originating page and CSV route are fixed by the fixture. For real workflows, add the report ID and requested revision or time window. If the app produces export IDs, use them to connect a delayed download with its originating action.
Step 2. Open the fixture with the correct browser
Start the local fixture and save the shared modules. The local client launches Chromium. The verifier also exercises the client through CDP on a temporary Chromium runtime. A managed test requires an authorized Nstdata workspace and a ready session. Supply the documented credential and session variables, then use an approved staging version of the fixture that the managed browser can reach. Verify the provider path in your workspace before depending on it. Cloud Browser automation reference.
const root ='https://api.nstdata.io/api/v1/cloud-browser';exportasyncfunctionapi(method, path, body){const key = process.env.NSTDATA_API_KEY;if(!key)thrownewError('Set NSTDATA_API_KEY');const headers ={'x-api-key': key };if(process.env.NSTDATA_TEAM_ID) headers['x-team-id']= process.env.NSTDATA_TEAM_ID;if(body) headers['content-type']='application/json';let response;try{ response =awaitfetch(root + path,{ method, headers,redirect:'error',body: body ?JSON.stringify(body):undefined,signal:AbortSignal.timeout(20_000),});}catch{throwObject.assign(newError('API transport failed; reconcile the original operation'),{retryable:true});}const retryable = response.status===429|| response.status>=500;let result;try{ result =await response.json();}catch{throwObject.assign(newError('Invalid API JSON'),{ retryable });}if(!response.ok|| result.err===true|| result.success===false){throwObject.assign(newError(`Cloud Browser API HTTP ${response.status}`),{ retryable });}if(!result.data)thrownewError('Missing API data');return result.data;}exportasyncfunctionconnection(id){if(!id)thrownewError('Set NSTDATA_SESSION_ID');const path =`/sessions/${encodeURIComponent(id)}`;const session =awaitapi('GET', path);if(session.state!=='ready')thrownewError(`Session is ${session.state}, not ready`);const c =awaitapi('POST', path +'/automation-credentials');if(c.sessionId!== id ||!c.headerName||!c.accessToken||!(Date.parse(c.expiresAt)>Date.now())||newURL(c.cdpUrl).protocol!=='wss:'){thrownewError('Invalid or expired CDP credentials');}return{endpoint: c.cdpUrl,headers:{[c.headerName]: c.headerName.toLowerCase()==='authorization'?`Bearer ${c.accessToken}`: c.accessToken},};}exportasyncfunctionendpoint(){// An isolated local CDP endpoint can test the client without managed credentials.if(process.env.LOCAL_CDP_URL){const url =newURL(process.env.LOCAL_CDP_URL);if(!['127.0.0.1','localhost','[::1]'].includes(url.hostname)){thrownewError('LOCAL_CDP_URL must use loopback');}return{endpoint: url.href,headers:{}};}returnconnection(process.env.NSTDATA_SESSION_ID);}
import{ chromium }from'playwright-core';import{ endpoint }from'./cloud-api.mjs';exportasyncfunctionwithPage(task){const origin =newURL(process.env.APP_ORIGIN??'http://127.0.0.1:4173');const remote =Boolean(process.env.LOCAL_CDP_URL|| process.env.NSTDATA_SESSION_ID);if(!remote && origin.hostname!=='127.0.0.1')throwError('Use the local fixture for local runs');const connection = remote ?awaitendpoint():null;const browser = connection
?await chromium.connectOverCDP(connection.endpoint,{headers: connection.headers,timeout:15_000}):await chromium.launch({args:['--no-proxy-server']});let page;try{const context = remote ? browser.contexts()[0]:await browser.newContext();if(!context)throwError('Expected a browser context'); page =await context.newPage(); page.setDefaultTimeout(8_000); page.setDefaultNavigationTimeout(10_000);returnawaittask(page, origin);}finally{try{await page?.close();}finally{await browser.close();}}}
Step 3. Wait for the download before saving it
Run node download.mjs with the fixture active. The script creates the event promise before clicking the export link. It confirms that the event came from the fixture's expected export route, saves the finished download under a controlled filename, and compares the bytes. It prints a checksum using the Node.js crypto API. The temporary directory is removed after the example. A production worker should copy an accepted artifact to approved storage before removing its staging file.
Record the artifact ID, validation result, checksum if your workflow uses one, and disposition under your retention policy. The example prints one accepted row and a SHA-256 hash. If a managed session was used, verify the controller stops it after the transfer. The browser session lifecycle guide explains the difference between disconnect and service-side stop.
[Screenshot: Show the authorized inventory fixture and a safe terminal result with row count and checksum. Exclude account details and signed addresses.]
Why is an export missing after you click Download?
A missing export can mean the application is still generating the report, the wrong page owns the download, browser transfer failed, or cleanup happened before the worker saved the file. Diagnose the earliest missing milestone.
Symptom
Evidence to gather
Corrective action
No download event
Export job indicator and initiating page
Follow the documented app status and listen on the page that receives the attachment
Event appears but file is absent
Transfer failure and save destination
Save before closing the context and confirm the worker's storage path
File is empty or invalid
Schema, expected revision and error response
Reject it and reconcile the original app export
Report appears twice
Job history and export identifier
Reuse the accepted result or reconcile before starting a new export
Valid output with no cleanup
Managed session status and stop owner
Keep cleanup tracked until the session is terminal
Some apps render a PDF inline or open a new page instead of sending an attachment. Match the workflow to what that app actually does. When an attachment contains data you are authorized to handle, validate the content without printing the file or signed URLs into general logs. The browser debugging walkthrough helps isolate the difference between a delayed browser event and a failed server request.
How can you detect a stale or partial CSV?
Detect stale or partial exports by checking the run's report identity, expected columns and required records after the transfer finishes. In a multi-row CSV, validate the schema and a server-defined count or version when available. Filenames and modification timestamps can be reused while the contents change. A strict fixture can compare exact bytes, while a changing production report often needs parsed, task-specific checks.
A browser tab might download a valid file for the wrong filter. Use the input task's expected range or revision to validate the output and retain enough information to reproduce the verdict. If an export ID exists, compare it with the job created by the action and treat mismatches as unresolved. Mark a valid artifact accepted before moving it to a protected destination.
How does Nstdata Cloud Browser fit a controlled export workflow?
Nstdata Cloud Browser provides a managed browser runtime for workflows that need interaction before an artifact becomes available. Use the supported CDP connection to reach the application and the client's download lifecycle to observe completion. Your application still chooses where to store authorized files, checks data quality, and schedules cleanup. A managed connection may have environment-specific artifact-transfer behavior, so make a custom fixture part of the integration test before scaling a job.
Interactive export. Use an owned session to operate the approved application and verify the artifact it produces.
Failure diagnosis. Inspect documented browser observations where available. Correlate them with export status rather than assuming the UI click finished the job.
Separate runtime cleanup. Release the browser when the accepted artifact is protected and terminal state is visible.
A reusable download test should prove that one approved action produced one expected file, the worker verified its contents, and both the artifact and browser were handled under known cleanup rules. Test a successful CSV, an explicit failure, and a report that completes after a visible wait. Keep the expected data independent from the capture script so a broken page cannot redefine success.
When visual confirmation is more useful than file transfer, use remote browser screenshot checks for a separate browser artifact and verify what each output actually proves.