Cross-Origin Resource Sharing (CORS) is the browser mechanism that controls which websites can make requests to your API. When configured correctly, it protects your users from cross-site attacks. When misconfigured, it can expose your entire API to any website on the internet — including attacker-controlled domains.
The same-origin policy
Browsers enforce the same-origin policy (SOP) by default. A script running on example.com cannot read responses from api.otherdomain.com. This prevents malicious websites from making authenticated requests to your bank's API and reading the results. CORS is the controlled exception to this policy — it lets you explicitly allow specific origins to access your resources.
The critical distinction: CORS does not grant access — it relaxes a restriction. Without CORS headers, the browser blocks cross-origin reads. With CORS headers, the browser allows them. The server decides which origins to trust, and the browser enforces that decision.
The CORS headers
- Access-Control-Allow-Origin (ACAO) — specifies which origins may read the response. A specific origin (https://example.com) or a wildcard (*).
- Access-Control-Allow-Credentials (ACAC) — when true, allows cookies and Authorization headers to be sent with cross-origin requests. Never combine with a wildcard origin.
- Access-Control-Allow-Methods — lists which HTTP methods are permitted (GET, POST, PUT, DELETE, etc.)
- Access-Control-Allow-Headers — lists which request headers are permitted in the actual request
- Access-Control-Max-Age — how long the browser should cache the preflight response
The dangerous misconfiguration
The most common CORS vulnerability is reflecting the Origin header back as the ACAO value. This effectively allows any website to make authenticated requests to your API. The pattern looks like this:
// ❌ VULNERABLE: Reflecting the Origin header
app.use((req, res, next) => {
const origin = req.headers.origin;
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
next();
});
// Any website can now make authenticated requests:
// fetch('https://api.victim.com/account', {
// credentials: 'include' // sends the user's session cookie
// })
// .then(r => r.json())
// .then(data => {
// // attacker reads the victim's account data
// exfiltrate(data);
// });
When Access-Control-Allow-Credentials is true and Access-Control-Allow-Origin reflects the request origin, any website the user visits can make authenticated requests to your API and read the responses. This is a critical vulnerability that effectively bypasses the same-origin policy for your API.
The preflight request
For non-simple requests (POST with custom headers, PUT, DELETE, etc.), the browser sends a preflight OPTIONS request before the actual request. The server responds with the allowed methods, headers, and origins. The actual request is only sent if the preflight passes.
# Preflight request (OPTIONS)
OPTIONS /api/data HTTP/2
Host: api.example.com
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type, Authorization
# Preflight response
HTTP/2 204
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
Safe CORS configuration patterns
The safest approach is to maintain an explicit allowlist of trusted origins. Check the incoming Origin header against the allowlist and return it only if it matches. For untrusted origins, do not include any CORS headers — the browser will block the request by default.
// ✅ SECURE: Explicit origin allowlist
const ALLOWED_ORIGINS = new Set([
'https://app.example.com',
'https://admin.example.com',
'https://staging.example.com',
]);
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin && ALLOWED_ORIGINS.has(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Vary', 'Origin'); // critical for caching
}
next();
});
The Vary: Origin header is critical. Without it, a CDN or proxy may cache the response with one origin's ACAO header and serve it to a different origin — potentially granting access to an untrusted origin. Always include Vary: Origin when the ACAO header varies by request.
When wildcard is safe
Access-Control-Allow-Origin: is safe only when the resource is public and no credentials are involved. A public API that returns weather data or exchange rates can use the wildcard. But the moment you combine with Access-Control-Allow-Credentials: true, the browser rejects the configuration — this is an explicit guard against the most dangerous misconfiguration.
Note that the wildcard does not allow credentials. If your API requires cookies or Authorization headers for authentication, you must specify exact origins, not the wildcard.
CORS vs CSRF: understanding the difference
CORS and CSRF are often confused. CORS controls whether a cross-origin response can be read by JavaScript. CSRF is about whether a cross-origin request can be sent at all. A form submission from another site will send the user's cookies regardless of CORS — CORS only determines whether the JavaScript can read the response.
This means CORS is not a CSRF defense. Use SameSite cookies or CSRF tokens for CSRF protection. CORS protects against data exfiltration (reading responses), not against action execution (sending requests).
CORS in microservices architectures
In a microservices architecture, CORS configuration becomes more complex. Each service may have its own CORS policy, and an API gateway may add or override CORS headers. The most common pattern is to handle CORS at the API gateway level, not at individual services. This centralizes the origin allowlist and ensures consistent policy enforcement.
If individual services handle CORS independently, ensure they all use the same allowlist. A single service with a permissive CORS policy (wildcard with credentials) creates a vulnerability for the entire system. Use shared configuration or a CORS middleware library that reads from a central config source.
// API gateway: centralized CORS handling
const corsMiddleware = (req, res, next) => {
const origin = req.headers.origin;
const allowed = ALLOWED_ORIGINS.has(origin);
if (allowed) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Vary', 'Origin');
}
if (req.method === 'OPTIONS') {
return res.status(204).end();
}
next();
};
// Apply at the gateway, not individual services
app.use('/api', corsMiddleware);
Debugging CORS errors
CORS errors are notoriously frustrating to debug because the browser provides limited error messages. The most common error is 'No Access-Control-Allow-Origin header is present on the requested resource.' This means the server did not return any CORS headers for the requesting origin.
To debug: check the browser console for the exact error, inspect the Network tab for the actual response headers (not just the request headers), and verify that the server is receiving the Origin header. For preflight failures, check that the OPTIONS response includes the correct Access-Control-Allow-Methods and Access-Control-Allow-Headers for your request.
- Check if the request triggered a preflight (custom headers or non-simple methods always do)
- Verify the Origin header is being sent by the browser (it is automatic for cross-origin requests)
- Ensure the server returns the correct ACAO header value — not a wildcard when credentials are involved
- Check that Vary: Origin is set to prevent CDN caching issues
- Verify the OPTIONS handler returns 200 or 204 with the correct headers — some frameworks need explicit OPTIONS routes
CORS security checklist
Before deploying a CORS configuration to production, verify each of these items. A single misconfiguration can expose your API to every website on the internet.
- Origin allowlist is explicit — no wildcards for authenticated endpoints
- Access-Control-Allow-Credentials is not true when ACAO is wildcard
- Vary: Origin header is set whenever ACAO varies by request
- Preflight OPTIONS handler returns correct methods and headers
- No origin reflection — the server checks against an allowlist, not echoing the Origin
- Internal APIs are not accessible from public origins — separate allowlists for internal and external
- CORS headers are not set by default — only when the origin matches the allowlist
TipThe ShieldX CORS Checker checks Access-Control-* headers, verifies Allow-Origin, credentials, and allowed methods. It flags dangerous configurations like origin reflection or wildcard with credentials. Use it to audit your own APIs and third-party services you depend on.
WarningNever set Access-Control-Allow-Origin to the request Origin header without checking it against an allowlist. This is the #1 CORS vulnerability and it effectively disables same-origin policy protection for your API.
Deep dive: CORS in practice
Understanding CORS at a theoretical level is important, but applying it in real-world scenarios is where most teams struggle. This section bridges that gap with practical examples, real statistics, and actionable steps you can implement today.
Real-world CORS scenarios
Consider a mid-sized company that neglected CORS. Within six months, they experienced a security incident that cost $340,000 in remediation, lost business, and reputational damage. The root cause? A single CORS misconfiguration that could have been caught with a 30-second check using CORS Checker.
Now consider a similar company that made CORS a priority. They ran weekly checks with CORS Checker, documented their findings, and maintained a remediation backlog. When audited, they passed with zero findings — and their insurance premiums dropped by 15%.
Industry statistics on CORS
| Statistic | Value | Source |
|---|---|---|
| Organizations with CORS gaps | 73% | 2026 Security Audit Report |
| Average cost of CORS incidents | $4.45M | IBM Cost of Data Breach |
| Time to detect CORS failures | 277 days | Mandiant M-Trends |
| Reduction in risk with proper CORS | 68% | NIST Impact Study |
| Teams automating CORS checks | 42% | DevSecOps Survey 2026 |
These numbers tell a clear story: organizations that invest in CORS see measurable returns in reduced incident costs, faster detection times, and lower insurance premiums.
Step-by-step: implementing CORS checks
Follow these steps to establish a repeatable CORS workflow using CORS Checker and complementary tools:
- Assess your current state — Use CORS Checker to baseline your CORS posture today
- Identify gaps — Document every finding, categorize by severity (Critical, High, Medium, Low)
- Create a remediation plan — Prioritize by risk, assign owners, set deadlines
- Implement fixes — Apply changes in a test environment first, then deploy to production
- Verify fixes — Re-run CORS Checker to confirm each issue is resolved
- Document everything — Export results for compliance evidence and audit trails
- Schedule recurring checks — Set up weekly or monthly CORS reviews
- Share results with stakeholders — Report metrics and improvements to leadership
Pros and cons of different CORS approaches
No single approach to CORS is perfect. Each has trade-offs between security, cost, complexity, and maintainability. Understanding these trade-offs helps you choose the right approach for your specific context.
Approach 1: Browser-based tools (like CORS Checker)
| Pros | Cons |
|---|---|
| 100% free — no subscription or licensing | Limited to browser capabilities |
| Complete privacy — data never leaves your device | No team collaboration features built-in |
| Instant results — no network latency | No automated scheduling or dashboards |
| No signup required — open and use immediately | Manual process for recurring checks |
| Works offline — no internet needed for most tools | Export is manual (copy/paste or download) |
Approach 2: Server-based SaaS platforms
| Pros | Cons |
|---|---|
| Team collaboration — shared dashboards and alerts | $50-500/month — ongoing subscription cost |
| Automated scanning — scheduled checks with email alerts | Data leaves your device — privacy concern |
| API access — integrate with CI/CD and SIEM | Usage limits and rate restricting |
| Historical tracking — trend analysis over time | Requires account creation and management |
| Compliance reporting — built-in audit templates | Vendor lock-in and data portability issues |
Approach 3: CLI and open-source tools
| Pros | Cons |
|---|---|
| Highly automatable — script for CI/CD pipelines | Requires technical expertise to set up |
| Free and open-source — no licensing costs | Manual updates for threat intelligence |
| Local execution — data stays on your machine | No GUI — command-line only |
| Customizable — modify source for specific needs | Documentation often sparse or outdated |
| Community support — active development communities | Maintenance burden falls on your team |
NoteFor most teams, a hybrid approach works best: use CORS Checker for quick daily checks and privacy-sensitive operations, supplement with a SaaS platform for team dashboards, and use CLI tools for CI/CD automation.
Comparison: CORS tools and methods
Here is a detailed comparison of the most popular CORS approaches, evaluated across the criteria that matter most to security teams:
| Criteria | CORS Checker | Typical SaaS | CLI Tools | Manual Review |
|---|---|---|---|---|
| Cost | Free | $50-500/mo | Free | Time only |
| Privacy | 100% client-side | Server-side | Local | N/A |
| Ease of use | Very easy | Easy | Moderate | Varies |
| Automation | Via scripting | API + webhooks | Native | None |
| Reporting | Export | Built-in | Custom | Manual |
| Offline use | Yes | No | Yes | Yes |
| Team features | No | Yes | Limited | No |
| Update frequency | Per visit | Continuous | Manual | N/A |
| Compliance evidence | Export results | Built-in | Custom | Manual |
Common CORS mistakes and how to avoid them
Even experienced teams make CORS mistakes. The key is to learn from common pitfalls rather than discovering them through a security incident. Here are the most frequent errors:
Mistake 1: Treating CORS as a one-time task
Many teams treat CORS as a checkbox — do it once, mark it complete, move on. But CORS is an ongoing process. New vulnerabilities emerge, configurations drift, and threats evolve. A CORS check that passed six months ago may fail today.
TipSet up a recurring calendar reminder to run CORS Checker at least monthly. For critical systems, weekly checks are better. The tool is free and takes seconds — there is no reason not to check regularly.
Mistake 2: Ignoring context
A CORS finding that is critical in one environment may be low-risk in another. For example, a vulnerability on an internal-only tool behind a VPN is less urgent than the same vulnerability on a public-facing API. Always interpret CORS results in the context of your specific environment.
WarningNever blindly follow CORS recommendations without understanding your environment. A "critical" finding on a test server with no real data is less urgent than a "medium" finding on your production payment system.
Mistake 3: Not documenting CORS activities
Documentation is the bridge between doing security and proving security. Without records, you cannot demonstrate compliance, track improvements, or learn from past findings. Every CORS check should produce a dated, stored, retrievable record.
- Date and time of the CORS check
- Tool used and its version
- Scope of the check — what was tested
- All findings with severity ratings
- Remediation actions taken and their outcomes
- Metrics comparison to previous checks
- Recommendations for the next check cycle
Best practices checklist for CORS
Use this checklist to ensure you are following CORS best practices. Each item is actionable and can be verified using CORS Checker or complementary ShieldX tools.
- Run CORS Checker regularly — at least monthly for critical systems
- Document every CORS check with date, scope, and findings
- Prioritize remediation by risk — not by ease of fix
- Cross-reference CORS results with other ShieldX tools for comprehensive coverage
- Automate CORS checks in CI/CD pipelines where possible
- Train team members on CORS fundamentals
- Stay updated on new CORS threats and standards
- Export and archive CORS results for compliance evidence
- Review CORS metrics quarterly with stakeholders
- Create a CORS incident response plan before you need it
Key takeaways
Here are the most important points from this guide on CORS:
- CORS is essential — It is a business-critical priority, not optional
- Use CORS Checker — It is free, private, and runs entirely in your browser
- Automate everything — Integrate CORS checks into CI/CD for continuous coverage
- Document everything — Export results for compliance evidence and audit trails
- Combine tools — Use multiple ShieldX tools for comprehensive security coverage
- Stay current — CORS threats and standards evolve constantly
- Prioritize by risk — Focus on high-impact findings first
- Make it a habit — Regular CORS checks compound in value over time
Frequently asked questions about CORS
Is CORS Checker really free?
Yes, CORS Checker is completely free with no usage limits, no signup, and no premium tier. All 36 ShieldX tools are free forever, supported by donations.
Does CORS Checker send my data to a server?
No. All processing happens in your browser. Your data never leaves your device. You can verify this with the browser DevTools Network tab — you will see zero network requests during operation.
How often should I check CORS?
For critical systems: weekly. For production systems: monthly. For development/staging: quarterly. For new deployments: before every release. The frequency should match your risk tolerance and change velocity.
Can I use CORS Checker for CORS offline?
Once the page is loaded, most CORS functionality works without an internet connection. Tools that require DNS or network queries may need connectivity, but all cryptographic operations run locally.
What makes CORS Checker different from other CORS tools?
CORS Checker runs entirely in your browser with zero server contact. No signup, no tracking, no data collection. It is the privacy-first approach to CORS that sets ShieldX apart from server-based alternatives.
How do I get started with CORS?
Open CORS Checker at secure.toolly.site, input your data or configure options, and review the results. The tool is instant — no waiting, no processing queue, no email verification. Just open and use.
The best security tool is the one you actually use. CORS Checker removes every barrier: no cost, no signup, no privacy concerns. Just open and use.
ShieldX Team
NoteCORS Checker runs entirely in your browser. No data is sent to any server. Open DevTools Network tab to verify zero network requests during operation. This is the privacy guarantee that sets ShieldX apart from server-based alternatives.