Implementation:Cypress io Cypress RewriteJs
| Knowledge Sources | |
|---|---|
| Domains | AST_Transformation, Proxy |
| Last Updated | 2026-02-12 00:00 GMT |
Overview
Concrete tool for rewriting JavaScript source code via AST transformation to enable cross-origin testing provided by the Cypress rewriter package.
Description
The rewriteJs function takes a URL and JavaScript source string, parses it into an AST using recast and ast-types, applies transformation rules (modifying window references, location access patterns, etc.), and returns the rewritten JavaScript. It handles source map rewriting for debugging support. On parse errors, it gracefully returns the original JavaScript unchanged.
Usage
This function is called by the HTTP proxy for every JavaScript file served to the browser during test execution. It enables Cypress to instrument application code for cross-origin testing support.
Code Reference
Source Location
- Repository: cypress-io/cypress
- File: packages/rewriter/lib/js.ts
- Lines: L98-107
Signature
export function rewriteJs(
url: string,
js: string,
deferSourceMapRewrite?: DeferSourceMapRewriteFn
): string
Import
import { rewriteJs } from '@packages/rewriter'
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| url | string | Yes | URL of the JavaScript file being rewritten |
| js | string | Yes | JavaScript source code to rewrite |
| deferSourceMapRewrite | DeferSourceMapRewriteFn | No | Callback to defer source map rewriting |
Outputs
| Name | Type | Description |
|---|---|---|
| rewritten JS | string | Modified JavaScript with Cypress instrumentation, or original JS on error |
Usage Examples
Proxy Integration
import { rewriteJs } from '@packages/rewriter'
// In the HTTP proxy response handler
const originalJs = responseBody.toString()
const rewrittenJs = rewriteJs(requestUrl, originalJs, deferSourceMapRewrite)
response.body = rewrittenJs