Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsUse Puppeteer request interception and compare each request’s exact origin with your main site’s origin. Add the Basic Auth Authorization header only when they match, and continue every other request without it. Because Puppeteer checks each request separately, the same rule applies to third-party resources and redirects.
Use request interception for an exact-origin rule
Request interception gives you a decision point for every request that the page initiates. Parse the request URL, compare its origin to the configured origin, and add the header only on an exact match. An origin includes the scheme, hostname, and port when one is present, so https://example.com is different from http://example.com and from https://example.com:8443.
The example below uses ES modules and Node.js. Set the credentials in the environment rather than embedding them in source code. Replace the example origin and path with your site’s values.
import puppeteer from 'puppeteer';
const mainOrigin = 'https://example.com';
const username = process.env.BASIC_AUTH_USER;
const password = process.env.BASIC_AUTH_PASSWORD;
if (!username || !password) {
throw new Error('Set BASIC_AUTH_USER and BASIC_AUTH_PASSWORD first.');
}
const basic = Buffer.from(`${username}:${password}`, 'utf8').toString('base64');
const authorization = `Basic ${basic}`;
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', request => {
let requestOrigin;
try {
requestOrigin = new URL(request.url()).origin;
} catch {
// A URL that cannot be parsed must not receive the credentials.
void request.continue();
return;
}
if (requestOrigin === mainOrigin) {
void request.continue({
headers: {
...request.headers(),
authorization,
},
});
} else {
void request.continue();
}
});
const response = await page.goto(`${mainOrigin}/private`, {
waitUntil: 'networkidle2',
});
console.log('Navigation status:', response?.status() ?? 'no response');
} finally {
await browser.close();
}
The Buffer conversion produces the Base64 portion of the Basic authentication value; it is encoding, not encryption. HTTPS protects the request in transit, but the credential should still be treated as a secret. Avoid printing the generated header or request headers to logs.
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
Run it with environment variables
Install Puppeteer in a project that supports ES modules, then provide credentials through your shell or secret manager. For example, in a POSIX-style shell:
npm install puppeteer
BASIC_AUTH_USER='your-user' BASIC_AUTH_PASSWORD='your-password' node capture.mjs
On Windows or in a deployment environment, use that environment’s supported method for setting secrets. Do not commit a real password, API key, or generated authorization value to source control.
Why the handler continues every request
When interception is enabled, each intercepted request must be resolved. The matching branch calls continue with the existing request headers plus the authorization value. The non-matching branch calls continue without adding it. If a request is left unresolved, it can stall or fail, so do not add conditional branches that forget to continue, abort, or otherwise resolve a request.
Match the origin, not a hostname fragment
Do not decide that a request is trusted because its hostname merely ends with your domain name. A loose suffix check can accept an attacker-controlled hostname such as example.com.attacker.test. It can also accidentally include sibling subdomains that should not receive credentials.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchRank #2
- HTML CSS Design and Build Web Sites
- Comes with secure packaging
- It can be a gift option
Exact origin comparison makes the intended boundary explicit:
https://example.commatches the configured origin.http://example.comdoes not match because the scheme differs.https://www.example.comdoes not match because the hostname differs.https://example.com:8443does not match the default HTTPS origin because the port differs.
If the application legitimately uses more than one trusted origin, define each full origin deliberately and compare against an allowlist of those origins. Do not broaden the rule to all subdomains unless every included host is trusted to receive the credentials.
Redirects and resources from other sites
A page can request more than its initial document: scripts, stylesheets, images, API endpoints, frames, and other resources may come from different origins. The interception callback checks each request independently, so a request to a third-party origin proceeds without the added header.
The same per-request check matters when navigation redirects. Do not assume that a credential added for the first URL remains appropriate for the redirect destination. With this handler, the destination request is evaluated against the configured origin again; if its origin differs, the added header is omitted. If a redirect returns to the configured origin, that new request meets the same exact-origin rule.
Rank #3
This rule governs the header your interception handler adds. Review any other authentication mechanism in your application separately, and do not treat a successful first navigation as proof that all subsequent requests are going to the intended hosts.
Why not use Puppeteer’s other header and authentication APIs?
The choice depends on scope. For a strict main-origin-only authorization header, the per-request check is the option that lets you implement that boundary directly.
| Option | Scope | Best fit | Important limitation |
|---|---|---|---|
| Request interception with exact-origin check | Each request, evaluated by URL | Adding a header only for a specified origin | You must resolve every intercepted request exactly once. |
page.authenticate |
HTTP authentication challenges handled for the page | One credential pair for the page’s authentication challenges | The API documents no host or origin allowlist. It also enables request interception behind the scenes, which may affect performance. Passing null disables authentication. See Puppeteer’s Page.authenticate documentation. |
page.setExtraHTTPHeaders |
Every request initiated by the page | Headers that are appropriate for all destinations | It is too broad for a domain-scoped authorization value. Puppeteer says extra headers are sent with every request the page initiates; names are lowercased and ordering is not guaranteed. See Puppeteer’s Page.setExtraHTTPHeaders documentation. |
Puppeteer’s HTTPRequest documentation describes the request information available to interception handlers. For the domain boundary in this article, inspect the URL and make the decision at the request level rather than setting a page-wide authorization header.
Common failures and how to fix them
The private page still returns an authentication error
- Confirm that the environment variables are set in the process that launches Node.js; the example deliberately stops if either is missing.
- Check that the username and password are the expected values, including any required punctuation or whitespace.
- Verify that
mainOriginexactly matches the requested scheme, hostname, and port. A mismatch means the handler continues the request without adding the header. - Check the navigation response status and the site’s authentication behavior. A 401 or 403 can have causes other than a missing Basic header, such as an incorrect account or access policy.
Third-party requests are receiving the header
Use the strict equality check shown here, not includes, endsWith, or a partial hostname match. Confirm that no separate call to setExtraHTTPHeaders or other code is also applying the authorization value to all page requests.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #4
- Brand: Wiley
- Set of 2 Volumes
- A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
The page hangs or requests fail after enabling interception
Audit every path in the request listener. Each request needs to be continued, aborted, or handled through an appropriate interception action; this example continues both matching and non-matching requests. Also check for another request listener that is attempting to resolve the same intercepted request, since resolving a request more than once is an error. Keep the handler small and avoid waiting on unrelated asynchronous work before resolving a request.
A redirect behaves differently from the first URL
Inspect the redirect destination’s origin. If it changes scheme, host, or port, it intentionally will not receive the header under this configuration. If the destination is a legitimate authentication endpoint, add its exact origin to an explicit allowlist only after confirming it is trusted to receive the credentials.
Code works locally but exposes a secret in deployment logs
Do not log the authorization header or serialize all request headers for debugging. Log only non-sensitive information such as the request origin and whether it matched the allowlist. Store credentials in the deployment platform’s secret mechanism and rotate them if they have been exposed.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Performance, reliability, and security trade-offs
Request interception adds work because each request passes through the handler, and page.authenticate also enables interception behind the scenes according to Puppeteer’s API documentation. Keep the callback synchronous and lightweight where possible. The code above parses one URL and performs one equality check, then resolves the request immediately.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Best Value
The primary reliability concern is not the comparison but incomplete interception handling: a missed continuation can prevent a resource or navigation from completing. The primary security advantage is least scope: credentials are attached only to requests whose origin exactly matches the configured one. That does not make Basic authentication a substitute for HTTPS or secure secret storage, and it does not make a trusted origin safe if that server itself is compromised.
Or skip the browser setup
If your goal is simply to produce a website screenshot rather than to build a Puppeteer workflow, ScreenshotNeo offers a screenshot API and MCP server. Its API accepts custom headers, including Authorization; consult the ScreenshotNeo documentation for request options and authentication details. The one-call example below captures a public page; it does not configure Basic Auth for the target.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo removes known consent banners, newsletter popups, and chat widgets before capture, with each cleanup step configurable. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; responses indicate the page verdict and billing status in headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000, and yearly billing gives two months free. See ScreenshotNeo, or sign up for 1,000 free screenshots a month with no card.
Frequently Asked Questions
Does Base64 encoding protect a Basic Auth password?
No. Base64 is an encoding, not encryption. Use HTTPS and protect the credential as a secret.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Can I allow two trusted origins instead of one?
Yes. Compare each parsed origin against an explicit allowlist of full origins, including scheme and port, and add the header only for a match.
Will this interception code add Basic Auth to a redirected request on the same origin?
Yes. Each request is checked anew, so a redirected request whose origin still exactly matches the configured origin qualifies.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

