Payment integrations are where sloppy CORS decisions turn into outages, failed checkouts, or security reviews nobody wants to sit through.
I’ve seen teams assume CORS is just a browser checkbox: add Access-Control-Allow-Origin: *, ship it, done. That logic falls apart fast in payments. Gateways deal with tokens, client secrets, redirects, idempotency keys, fraud signals, and sometimes session cookies. The browser is the least trustworthy place in that chain, so your CORS policy has to reflect that.
Here’s the practical comparison: when CORS works well for payment gateway integrations, when it becomes a liability, and which architecture tends to age better.
The core question
When integrating a payment gateway from the browser, you usually have three models:
- Direct browser-to-gateway API calls
- Browser-to-your-backend, then backend-to-gateway
- Hosted fields / embedded payment UI / redirect flows
CORS matters most in the first model, a little in the second, and often barely at all in the third.
Option 1: Direct browser-to-gateway API calls
This is the “single-page app talks straight to the payment provider” setup.
Example:
const res = await fetch("https://gateway.example.com/v1/payment_methods", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${publishableKey}`
},
body: JSON.stringify({
cardNumber: "4111111111111111",
expMonth: "12",
expYear: "2028",
cvc: "123"
})
});
Pros
- Lower latency for some flows
- Less backend code on your side
- Cleaner frontend prototypes
- Useful for tokenization when the gateway explicitly supports public client-side APIs
Cons
- Very limited by gateway CORS policy
- You expose integration details in the browser
- You cannot safely use secret credentials
- Preflight requests add failure points
- Debugging gets ugly across environments
- Compliance review gets harder if you handle raw card data badly
This model only works if the payment provider intentionally exposes browser-safe endpoints. That usually means tokenization endpoints with public keys, not charge creation, refund operations, or anything that uses your secret API key.
If your team is trying to call a gateway’s “server API” directly from React because “it works in Postman,” stop there. Postman does not enforce browser CORS. Browsers do.
CORS requirements for this model
A browser request will only succeed if the gateway returns the right CORS headers. Typical examples:
Access-Control-Allow-Origin: https://shop.example
Access-Control-Allow-Methods: POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600
If credentials are involved:
Access-Control-Allow-Origin: https://shop.example
Access-Control-Allow-Credentials: true
Not this:
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
That combination is invalid for credentialed requests.
For a real-world reference, api.github.com returns:
access-control-allow-origin: *
access-control-expose-headers: ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset, Warning
That works for GitHub’s public API use cases, but payment APIs are rarely that permissive. For payments, wildcard origin support is usually too broad unless the endpoint is strictly public and heavily constrained.
Option 2: Browser to your backend, backend to gateway
This is the default architecture I recommend.
The frontend calls your own API:
const res = await fetch("/api/checkout/create-payment-intent", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
credentials: "include",
body: JSON.stringify({
cartId: "cart_123"
})
});
Then your server talks to the gateway:
app.post("/api/checkout/create-payment-intent", async (req, res) => {
const gatewayRes = await fetch("https://gateway.example.com/v1/payment_intents", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env.GATEWAY_SECRET_KEY}`
},
body: JSON.stringify({
amount: 4999,
currency: "USD"
})
});
const data = await gatewayRes.json();
res.json(data);
});
Pros
- Your secret keys stay off the client
- CORS complexity is reduced to your own origin policy
- You can enforce auth, fraud checks, inventory rules, and idempotency
- You get better logging and error handling
- Easier to rotate providers later
Cons
- More backend work
- Slightly more latency
- You must secure and scale your own API
- Bad backend design can accidentally expand PCI scope
This is usually the safest and most flexible model. You keep your blast radius smaller. You also avoid relying on each gateway’s browser behavior, which can differ a lot between products, regions, and older API versions.
If you own the backend, you can make CORS boring. That’s a good thing.
Recommended CORS policy for your payment API
Be strict:
app.use((req, res, next) => {
const allowedOrigins = new Set([
"https://shop.example",
"https://staging.shop.example"
]);
const origin = req.headers.origin;
if (origin && allowedOrigins.has(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Vary", "Origin");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Requested-With");
}
if (req.method === "OPTIONS") {
return res.sendStatus(204);
}
next();
});
A few opinions here:
- Don’t use
*on authenticated payment endpoints. - Don’t reflect arbitrary origins without an allowlist.
- Don’t allow every method and header “just in case.”
- Add
Vary: Originwhen dynamically setting origins, or caches can betray you.
Option 3: Hosted fields, embedded widgets, and redirects
This is often the cleanest path for payments.
Instead of your frontend posting card data to your backend or the gateway API directly, the provider gives you:
- hosted card fields in iframes
- a checkout widget
- a redirect to a payment page
- a client SDK that tokenizes card data inside provider-controlled origins
Pros
- Much lower CORS surface area
- Less PCI pain
- Provider handles sensitive input
- Usually better fraud tooling and SCA support
- Fewer browser compatibility surprises
Cons
- Less UI control
- Can be harder to fully customize
- SDK behavior can feel opaque
- Provider lock-in is stronger
For most teams, this is the best tradeoff. You lose some purity and control, but you also avoid reinventing a high-risk flow. I’d take that deal almost every time.
Comparison table
Direct browser-to-gateway
Best for: tokenization with publishable keys
CORS complexity: high
Secret handling: weak
Customization: high
Security posture: depends heavily on provider design
Backend proxy/integration
Best for: most custom checkout flows
CORS complexity: moderate, but under your control
Secret handling: strong
Customization: high
Security posture: strongest for most teams
Hosted fields / redirect / widget
Best for: fast, compliant, low-risk launches
CORS complexity: low
Secret handling: strong
Customization: medium
Security posture: usually very good
Common CORS mistakes in payment integrations
1. Using wildcard origins on sensitive endpoints
This is fine for truly public resources. It is not fine for checkout APIs tied to sessions, carts, or customer state.
2. Forgetting preflight behavior
A request with Authorization or Content-Type: application/json will often trigger an OPTIONS preflight.
If your API gateway, CDN, or WAF drops OPTIONS, checkout breaks before the real request even starts.
3. Exposing too many response headers
If the browser needs to read custom response headers, expose only what you need:
Access-Control-Expose-Headers: Idempotency-Key, Request-Id
GitHub exposes a long list because its API has different needs. Payments usually need much less. Keep it tight.
4. Mixing cookies with bad CORS rules
If your checkout relies on session cookies:
- use
credentials: "include"in fetch - return
Access-Control-Allow-Credentials: true - return a specific allowed origin, not
*
And make sure your cookie settings are correct too. CORS alone won’t save a broken cookie policy. If you’re reviewing adjacent security headers, https://csp-guide.com is a good reference for CSP decisions around payment scripts and frames.
5. Treating CORS as auth
CORS is a browser enforcement layer, not an authentication mechanism. Attackers can still hit your API from curl, mobile apps, or servers. Your payment endpoints still need real auth, authorization, rate limits, and replay protection.
My recommendation
If you’re building a payment integration for a production web app:
- Use hosted fields or the provider’s browser-safe SDK for card entry
- Use your backend for payment intent creation, order validation, and final confirmation
- Keep CORS strict on your own API
- Avoid direct browser calls to secret-bearing gateway endpoints
- Only rely on gateway CORS support where the provider explicitly documents it
That last part matters. If the docs don’t clearly say “this endpoint is intended for browser use,” I assume it is not.
Official docs are the only place I trust for that boundary:
- MDN CORS reference
- Fetch standard
- Your payment provider’s official API and frontend SDK docs
For payment work, the best CORS setup is usually the one you barely notice because your architecture avoided the risky path in the first place.