How to Open Local Files with Relative References in Puppeteer Firefox
Open local HTML in Puppeteer Firefox with working relative assets using file URLs, pathToFileURL, reliable waits, and practical troubleshooting.

Direct answer: launch current Puppeteer with browser: 'firefox', resolve your HTML file to an absolute path, convert it with Node.js pathToFileURL(), and pass the resulting file: URL to page.goto(). Relative images, stylesheets and scripts then resolve from the HTML file’s directory.
import puppeteer from 'puppeteer';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
const browser = await puppeteer.launch({ browser: 'firefox' });
try {
const page = await browser.newPage();
const htmlPath = path.resolve('fixtures/report/index.html');
const fileUrl = pathToFileURL(htmlPath).href;
await page.goto(fileUrl, { waitUntil: 'networkidle0' });
await page.screenshot({ path: 'report.png', fullPage: true });
} finally {
await browser.close();
}
page.goto() expects a URL with a scheme such as https: or file:; a bare operating-system path is not a URL. Puppeteer’s API documents this requirement in the Page.goto reference. Node’s pathToFileURL documentation explains why converting an absolute path is safer than concatenating file:// yourself.
1. Arrange the local project so relative paths have a clear base
A browser resolves ./report.css, ../images/chart.png and similar references against the document URL. Keep the assets where the HTML expects them:

project/
├── fixtures/
│ └── report/
│ ├── index.html
│ ├── report.css
│ ├── app.js
│ └── images/
│ └── chart.png
└── scripts/
└── capture.mjs
In index.html, these references point to files in that tree:
<link rel="stylesheet" href="./report.css">
<img src="./images/chart.png" alt="Sales chart">
<script type="module" src="./app.js"></script>
Navigate to fixtures/report/index.html, not to the project directory. The directory containing the selected HTML document becomes the base for relative URLs.
2. Install Puppeteer and select Firefox
First-class Firefox support was announced for Puppeteer 23. Mozilla’s announcement shows the launch form used here: Mozilla Hacks: Official Puppeteer support for Firefox.
npm install puppeteer
Use an ES module file (for example, capture.mjs) or set "type": "module" in package.json. Then launch with:
const browser = await puppeteer.launch({
browser: 'firefox',
headless: true
});
If your installed version does not recognize browser: 'firefox', upgrade Puppeteer. The older puppeteer-firefox package and reports from 2019 describe a different integration; they do not establish how current Puppeteer behaves.
3. Convert paths correctly on every operating system
Always resolve first, then convert:
const absolutePath = path.resolve(process.cwd(), 'fixtures/report/index.html');
const url = pathToFileURL(absolutePath).href;
This handles spaces, #, %, non-ASCII characters and Windows drive letters. Manually writing 'file://' + filePath can turn a fragment marker or percent sign into URL syntax, changing the file that Firefox opens. The Node URL documentation includes examples of these encoding errors.
You can verify the exact target before navigation:
console.log({ absolutePath, url });
// /work/project/fixtures/report/index.html
// file:///work/project/fixtures/report/index.html
On Windows, let pathToFileURL() create the URL instead of trying to assemble file:///C:/... yourself.
4. Wait for the assets your capture actually needs
waitUntil: 'networkidle0' is useful for pages whose resources finish promptly, but local pages can contain long-running connections or scripts that never become idle. Choose the least broad wait that matches the page:
await page.goto(fileUrl, { waitUntil: 'domcontentloaded' });
await page.waitForSelector('#report-ready');
await page.screenshot({ path: 'report.png', fullPage: true });
Other navigation values are 'load', 'domcontentloaded' and 'networkidle2'. A selector wait is often more deterministic than a fixed sleep:
await page.goto(fileUrl, { waitUntil: 'load' });
await page.waitForFunction(() => document.fonts.status === 'loaded');
await page.waitForSelector('img[data-loaded="true"]');
If the document itself marks readiness, set that marker in your local script after charts, fonts or data transforms finish. For a simple static file, load plus an explicit image check is usually enough.
5. Use a complete diagnostic script
This script logs the final file URL, failed requests, browser console messages and page errors before taking a screenshot:
import puppeteer from 'puppeteer';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
const browser = await puppeteer.launch({ browser: 'firefox' });
try {
const page = await browser.newPage();
page.on('requestfailed', request => {
console.error('request failed', request.url(), request.failure()?.errorText);
});
page.on('console', message => console.log('console:', message.type(), message.text()));
page.on('pageerror', error => console.error('page error:', error));
const htmlPath = path.resolve('fixtures/report/index.html');
const fileUrl = pathToFileURL(htmlPath).href;
console.log('opening', fileUrl);
await page.goto(fileUrl, { waitUntil: 'load', timeout: 30_000 });
await page.waitForFunction(() => document.fonts.status === 'loaded');
await page.screenshot({ path: 'report.png', fullPage: true });
} finally {
await browser.close();
}
A failed request event tells you which URL Firefox attempted. Console and page-error events distinguish a missing file from a JavaScript exception that prevented the page from adding content.
6. Why page.setContent() often breaks relative assets
page.setContent(html) injects markup into a page. It is not documented as preserving the directory of an HTML file that you read separately, so relative references may have no useful filesystem base. Puppeteer’s files guide documents file uploads, not a guarantee that setContent() behaves like navigating to a local document.
Prefer reading the real file through page.goto(fileUrl). If you must inject markup, make every resource URL explicit:
import fs from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
const html = await fs.readFile('fixtures/report/index.html', 'utf8');
const cssUrl = pathToFileURL(path.resolve('fixtures/report/report.css')).href;
const rewritten = html.replace('./report.css', cssUrl);
await page.setContent(rewritten, { waitUntil: 'load' });
Rewriting can also be applied to images, module scripts and CSS url(...) references, but it is easy to miss one. Test the exact Firefox and Puppeteer versions used in production.
7. Local-file edge cases
Spaces, punctuation and Unicode
Use pathToFileURL(path.resolve(...)). A filename such as sales #2/report %.html must be percent-encoded in the URL; raw concatenation can interpret #2 as a fragment and truncate the path.
CSS and nested references
CSS URLs resolve relative to the stylesheet, not the HTML file. If report.css contains url('./fonts/Inter.woff2'), the font must be under the stylesheet’s directory. The same rule applies to imported CSS.
Modules and MIME behavior
Use a valid type="module" script path and watch the console for module errors. If a local module relies on fetch, dynamic imports or other browser features that are restricted for file: documents, serve the directory over HTTP instead.
When a local HTTP server is better
A tiny static server avoids file-origin restrictions and matches deployment behavior:
npx http-server fixtures/report -p 8080
# then navigate to http://127.0.0.1:8080/
Use this when the page needs fetch requests, service workers, CORS behavior or server-like routing. The file URL method remains the shortest path for a self-contained document and local assets.
8. Troubleshooting checklist
| Symptom | Likely cause | Fix |
|---|---|---|
Cannot navigate to invalid URL |
A bare filesystem path was passed to goto(). |
Resolve it and use pathToFileURL(...).href. |
| Images or CSS are missing | The document is not at the expected directory, or a relative path is wrong. | Log the file URL, check each path relative to the HTML file, and listen for requestfailed. |
Paths containing # or % fail |
Raw string concatenation created an invalid URL. | Use Node’s URL helper. |
| Firefox will not launch | Old Puppeteer version or an unavailable browser binary. | Upgrade Puppeteer and launch with browser: 'firefox'; record the Puppeteer and Firefox versions. |
setContent() page has blank assets |
Injected markup does not retain the source file’s directory. | Navigate to the real file URL or rewrite references to explicit URLs. |
| Navigation times out | A page waits forever for a connection or script. | Use domcontentloaded or load, then wait for a specific selector; raise timeout only when justified. |
| Screenshot is taken before charts render | Navigation completed before application rendering. | Wait for a ready selector, a font state, or an application-defined flag. |
| Fetch or service worker behavior differs | Firefox security rules for file: origins. |
Serve the directory over localhost and test through HTTP. |
For a stubborn failure, create a minimal reproduction containing the Puppeteer version, Firefox version, operating system, exact file URL and one relative asset. A 2019 Stack Overflow report describes a legacy puppeteer-firefox case, but it cannot prove that current Puppeteer reproduces the same issue.
9. Reliability, speed and security considerations
Reliability
- Use an absolute path derived from a known working directory, not an assumed process location.
- Close the browser in a
finallyblock so failures do not leave Firefox processes running. - Record request failures and console errors in CI logs.
- Pin Puppeteer and Firefox versions when pixel output matters, then update deliberately.
Performance
- Reuse one browser process for multiple files, creating a fresh page per capture.
- Prefer
domcontentloadedplus a readiness selector over an indefinite network-idle wait. - Keep local assets local and avoid unnecessary large images or fonts.
- Set a practical navigation timeout and fail with diagnostics rather than waiting forever.
Security
A local HTML file can execute JavaScript included in the document. Treat repositories and generated fixtures as code. Do not open untrusted HTML in a browser profile that contains personal credentials, and avoid granting unnecessary access to sensitive directories. If the page needs network access, a controlled localhost server makes origins and allowed resources easier to reason about.
10. Or skip the browser setup
If your goal is a clean screenshot of a public URL rather than testing a local file, ScreenshotNeo provides a single HTTP request. Its API can return PNG, JPEG, WebP or PDF, and the API documentation lists all 63 options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const buffer = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', buffer));
Cookie banners, newsletter popups and chat widgets are removed before the shot, with each cleanup step configurable. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed; response headers identify the page verdict and billing result with X-Page-Verdict and X-Billed. An MCP server lets Claude, Cursor and other MCP clients call take_screenshot, get_page_info and capture_pdf. The Free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots.
Create a free ScreenshotNeo account and try the API without a card.
11. FAQ
Can I pass a relative path directly to page.goto()?
No. Convert an absolute filesystem path to a file: URL first.
Does Firefox support local files in Puppeteer?
Current Puppeteer has first-class Firefox support from version 23. Local resource access still depends on valid paths and Firefox’s file-origin rules.
Should I use networkidle0 for every screenshot?
No. Use a readiness selector or application signal when pages have persistent connections.
Why do CSS images fail while the HTML image works?
CSS URLs resolve from the CSS file’s directory. Check that nested path, font and import locations.
When should I use localhost instead of file:?
Use localhost for fetch, service workers, CORS tests, routing or behavior that requires an HTTP origin.


