Building a 100% browser-side PDF Unlocker sounds straightforward until you hit two real-world traps:
- The PDF Security Model: Users expect every "locked" PDF to behave the same way, but PDFs actually have two completely different password layers (Owner Permissions Lock vs. User Open Encryption).
- The Production
.mjsWorker Trap: Your Vite +pdfjs-distbuild works flawlessly onlocalhost, then immediately crashes in production on Apache/LiteSpeed hosting withSetting up fake worker failed: Failed to fetch dynamically imported module ...pdf.worker.min.mjs.
Here is how client-side PDF inspection and decryption actually work in TypeScript — plus the 1-line server header fix that prevents silent worker failures in production.
Owner Lock vs. User Encryption: Know the Difference
Every encrypted PDF contains an /Encrypt dictionary in its file trailer, but the encryption behaves very differently depending on which password was set:
| Lock Type | Opens Without Password? | What It Blocks | Can Be Unlocked Without Knowing Password? |
|---|---|---|---|
| Owner / Permissions Lock | Yes (empty user password "") | Printing, copying text, editing, form filling | Yes — PDF readers decrypt the stream automatically using the empty string |
| User Open Password | No (PasswordException) | Reading the document at all (RC4 / AES stream encryption) | No — Requires the valid open password to derive the decryption key |
If your frontend blindly asks every user for a password, owner-locked bank statements and invoices feel broken. Conversely, if you try to strip encryption without detecting /Encrypt, pdf-lib will either throw or preserve broken object streams.
Step 1: Classify the Lock State in the Browser
Before rendering or asking for a password, inspect the raw ArrayBuffer tail and head for the /Encrypt dictionary token, then probe the document with pdfjs-dist:
export type PdfLockStatus = "unlocked" | "owner-locked" | "user-locked"; let pdfjsConfigured = false; async function getPdfJs() { const [pdfjsLib, workerModule] = await Promise.all([ import("pdfjs-dist"), import("pdfjs-dist/build/pdf.worker.min.mjs?url"), ]); if (!pdfjsConfigured && pdfjsLib.GlobalWorkerOptions) { pdfjsLib.GlobalWorkerOptions.workerSrc = workerModule.default; pdfjsConfigured = true; } return pdfjsLib; } function bufferContainsEncryptDict(buffer: ArrayBuffer): boolean { const bytes = new Uint8Array(buffer); const decoder = new TextDecoder("latin1"); // Standard PDF trailers live near the tail; linearized PDFs may declare it near the head const tailStart = Math.max(0, bytes.length - 65536); if (/\/Encrypt\b/.test(decoder.decode(bytes.subarray(tailStart)))) return true; const headEnd = Math.min(bytes.length, 32768); return /\/Encrypt\b/.test(decoder.decode(bytes.subarray(0, headEnd))); } export async function inspectPdfLockStatus(buffer: ArrayBuffer) { const hasEncryptDict = bufferContainsEncryptDict(buffer); const pdfjsLib = await getPdfJs(); // Pass a slice() so PDF.js transferring the buffer to the Web Worker doesn't detach the caller's ArrayBuffer const loadingTask = pdfjsLib.getDocument({ data: new Uint8Array(buffer.slice(0)), }); try { const pdfDoc = await loadingTask.promise; return { status: (hasEncryptDict ? "owner-locked" : "unlocked") as PdfLockStatus, pageCount: pdfDoc.numPages, }; } catch (err: any) { if (err?.name === "PasswordException") { return { status: "user-locked" as PdfLockStatus, pageCount: 0 }; } throw err; } finally { await loadingTask.destroy().catch(() => {}); } } Two Subtle Details That Prevent Bugs
- Always pass
buffer.slice(0)topdfjsLib.getDocument: PDF.js transfers theUint8Array's underlyingArrayBufferto its Web Worker. If you pass the originalArrayBuffer, any subsequent unlock/export call fails with a detached ArrayBuffer error. - Always lazy-load
pdfjs-distwith dynamicimport(): Keep the multi-hundred-KB PDF worker bundle completely out of your main landing page chunk until the user actually drops a PDF.
Step 2: Unlocking Without Server Uploads
Once classified, you have two clean paths:
- Unlocked PDF (
!hasEncryptDict): Perform a fast, lossless copy viapdf-lib(PDFDocument.load->copyPages->save()). - Encrypted PDF (
owner-lockedoruser-locked): Decrypt withpdfjs-dist(usingpassword: userPassword || undefined), rebuild a clean unencrypted PDF with zero permission flags, and explicitly release each page's<canvas>memory (canvas.width = 0; canvas.height = 0; page.cleanup();) so large 50-page documents never crash mobile Safari.
// Distinguish "missing password" vs "wrong password" cleanly in the UI try { pdfDoc = await loadingTask.promise; } catch (err: any) { if (err?.name === "PasswordException") { if (err?.code === 2) { throw new Error("Incorrect password. Please enter the exact open password."); } throw new Error("This PDF requires a User Open Password to unlock."); } throw err; } Step 3: The Production Gotcha — The .mjs Worker MIME Trap
Everything above will pass TypeScript, build cleanly in Vite, and work locally on http://localhost:3000.
Then you deploy your static bundle to shared hosting (Apache / LiteSpeed / Hostinger) and open the tool. Boom:
Setting up fake worker failed: "Failed to fetch dynamically imported module: https://yoursite.com/assets/pdf.worker.min-xxxx.mjs" Why This Happens
Modern pdfjs-dist ships its worker as an ES module (.mjs). Vite emits assets/pdf.worker.min-[hash].mjs and loads it via dynamic import().
Many Apache and LiteSpeed servers do not have a default MIME type registered for .mjs, so they serve the worker with:
content-type: text/plain x-content-type-options: nosniff Strict browser MIME checking immediately rejects executing a text/plain ES module!
The 1-Line .htaccess Fix
Add .mjs explicitly to your public/.htaccess (and include it in your cache rules):
# Serve ES Module workers (.mjs) as valid JavaScript (required for PDF.js v4+/v5+) AddType text/javascript .mjs <IfModule mod_expires.c> ExpiresActive On ExpiresByType text/javascript "access plus 1 year" </IfModule> Verify immediately after deploying with curl:
curl -sI https://yoursite.com/assets/pdf.worker.min-xxxx.mjs | grep -i content-type # Expected: content-type: text/javascript Try Both Privacy-First PDF Tools Live
We use this exact zero-upload architecture across our browser PDF suite so sensitive bank statements, contracts, and tax returns never leave the user's device:
- OmniTools Unlock PDF — Auto-detects owner locks vs. user open passwords and strips restrictions 100% client-side.
- OmniTools Protect PDF — Adds real user/owner passwords and granular print/copy/edit permissions directly in the browser.
Key Takeaways
- Treat Owner Lock and User Password as distinct states in your UI — never make users type a password when
/Encryptonly restricts printing/copying. - Always pass
buffer.slice(0)intopdfjs-distto avoid detachedArrayBuffercrashes across worker boundaries. - Always test your production
pdf.worker.min.mjsresponse headers withcurl -sI— if your server returnstext/plainundernosniff,AddType text/javascript .mjsfixes it instantly.
Have you run into .mjs MIME issues or Web Worker memory limits when processing PDFs in the browser? Drop your war stories in the comments!