Why We Replaced SheetJS ([email protected]) With a 460-Line Zero-CVE OOXML Codec in Next.js & Cloudflare Workers
If you run npm audit on almost any JavaScript project that reads or writes Excel spreadsheets, you have probably seen this warning: xlsx * Severity: high Prototype Pollution in sheetJS - GHSA-4r6h-8v6p-xvw6 SheetJS R
If you run npm audit on almost any JavaScript project that reads or writes Excel spreadsheets, you have probably seen this warning:
xlsx *
Severity: high
Prototype Pollution in sheetJS - GHSA-4r6h-8v6p-xvw6
SheetJS Regular Expression Denial of Service (ReDoS) - GHSA-5pgg-2g8v-p4x9
No fix available
SheetJS stopped publishing security updates to the public npm registry after 0.18.5. For teams deploying Next.js applications to Cloudflare Workers, leaving an unpatched high-severity dependency in production is a recurring security audit headache β and pulling the full xlsx library statically also adds roughly 400 KB to client bundles even when a user never clicks "Export XLSX".
While auditing ToolsMetrics (a privacy-first suite of 198 client-side web tools and calculators running on Next.js 16 + OpenNext Cloudflare Workers), we looked at what our three Excel-enabled tools actually needed:
- Reading
.xlsx(OOXML) and UTF-8.csvfiles into 2D string matrices (string[][]). - Writing one or more 2D matrices into a valid
.xlsxdownload readable by Microsoft Excel, LibreOffice Calc, and Google Sheets.
We didn't need Excel 97β2003 BIFF macros, pivot-table formulas, or chart XML. And we already had jszip and papaparse in package.json with zero vulnerabilities.
What a Minimal Valid .xlsx File Actually Contains
An .xlsx file is just a ZIP archive containing 6 small XML files:
workbook.xlsx
βββ [Content_Types].xml
βββ _rels/.rels
βββ xl/
βββ workbook.xml
βββ _rels/workbook.xml.rels
βββ styles.xml
βββ worksheets/
βββ sheet1.xml
Using t="inlineStr" for text cells avoids building a separate sharedStrings.xml index on write, while t="n" and t="b" preserve native numbers and booleans:
function columnIndexToLetters(colIdx: number): string {
let n = colIdx + 1;
let letters = '';
while (n > 0) {
const rem = (n - 1) % 26;
letters = String.fromCharCode(65 + rem) + letters;
n = Math.floor((n - 1) / 26);
}
return letters;
}
function buildWorksheetXml(rows: SpreadsheetCell[][]): string {
const rowXmlParts: string[] = [];
for (let r = 0; r < rows.length; r++) {
const row = rows[r];
if (!Array.isArray(row) || row.length === 0) continue;
const rowNum = r + 1;
const cellXmlParts: string[] = [];
for (let c = 0; c < row.length; c++) {
const val = row[c];
if (val === null || val === undefined || val === '') continue;
const cellRef = `${columnIndexToLetters(c)}${rowNum}`;
if (typeof val === 'number' && Number.isFinite(val)) {
cellXmlParts.push(`<c r="${cellRef}" t="n"><v>${val}</v></c>`);
} else if (typeof val === 'boolean') {
cellXmlParts.push(`<c r="${cellRef}" t="b"><v>${val ? 1 : 0}</v></c>`);
} else {
const str = String(val);
const preserveAttr = /^\s|\s$|\n/.test(str) ? ' xml:space="preserve"' : '';
cellXmlParts.push(
`<c r="${cellRef}" t="inlineStr"><is><t${preserveAttr}>${escapeXml(str)}</t></is></c>`
);
}
}
if (cellXmlParts.length > 0) {
rowXmlParts.push(`<row r="${rowNum}">${cellXmlParts.join('')}</row>`);
}
}
return (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
`<sheetData>${rowXmlParts.join('')}</sheetData>` +
'</worksheet>'
);
}
Three subtle details matter in real-world spreadsheets:
-
Strip invalid XML 1.0 control characters (
[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]) before escaping& < > " ', otherwise Excel pops up a "corrupted content" recovery dialog. -
Sanitize sheet names: max 31 characters, strip
: \ / ? * [ ], trim leading/trailing apostrophes, and deduplicate case-insensitively. -
Honor sparse columns on read: Excel omits empty cells in
<row>XML, so<c r="A1">followed by<c r="C1">must pad columnBwith''rather than shifting columnCleft.
Reading External Excel Files (sharedStrings.xml + Rich-Text Runs)
While writing can use inlineStr, spreadsheets exported by Microsoft Excel and Google Sheets almost always store strings in xl/sharedStrings.xml, sometimes split across multiple <r><t> rich-text runs inside a single <si> node:
<si>
<r><t>RomΓ’</t></r>
<r><t>nia</t></r>
</si>
Parsing every <t> child inside each <si> block and joining them handles both plain <si><t> and styled rich-text cells cleanly without needing a heavy DOM parser β so the same codec works identically in browsers, Cloudflare Workers, and Node.js unit tests.
Bonus Win: Lazy-Loading on Export
Previously, our CSV & Excel Repair Studio and XML Sitemap Suite imported xlsx at the top of the module. Switching our new codec to a dynamic await import('@/utils/xlsxCodec') inside the upload/export click handlers meant users who only inspect CSVs or XML sitemaps download 0 KB of spreadsheet/ZIP code on initial page load.
Results
-
Production
npm audit --omit=dev:0High / Critical / Moderate vulnerabilities. -
Bundle reduction: Removed
[email protected]completely (~400 KB uncompressed) and lazy-loaded OOXML code on demand. -
Live demos: You can test the client-side
.xlsximport/export directly in the browser (100% offline, no file uploads) in our CSV & Excel Repair Studio and PDF to Excel / Office Converter (whose core document engine is also open-sourced aspdf-office-document-engine).
If your app only needs tabular .xlsx import/export and you are tired of staring at unpatchable [email protected] advisories, writing a focused, well-tested OOXML codec on top of jszip takes an afternoon and pays dividends in both security and bundle size.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.