Fix CORS Wildcard with Credentials Error
In this tutorial, you'll learn about Fix CORS Wildcard with Credentials Error. We cover key concepts, practical examples, and best practices.
You set Access-Control-Allow-Origin: * on your API and also need to send cookies or authorization headers with credentials: 'include' in fetch. The browser blocks the response because the CORS spec forbids wildcard origins when credentials are enabled.
Wrong
The server uses a wildcard origin while the frontend sends credentials.
Server side:
const cors = require('cors');
app.use(cors({ origin: '*' }));
Frontend side:
fetch('https://api.example.com/user', {
credentials: 'include'
})
.then(res => res.json());
Access to fetch at 'https://api.example.com/user' from origin
'https://app.example.com' has been blocked by CORS policy:
The value of the 'Access-Control-Allow-Origin' header in the response
must not be the wildcard '*' when the request's credentials mode is 'include'.
Right
Replace the wildcard with the exact requesting origin and explicitly allow credentials.
Server side:
const cors = require('cors');
app.use(cors({
origin: 'https://app.example.com',
credentials: true,
}));
Or for multiple origins with dynamic resolution:
const allowedOrigins = ['https://app.example.com', 'https://admin.example.com'];
app.use(cors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true,
}));
Frontend side (unchanged):
fetch('https://api.example.com/user', {
credentials: 'include'
})
.then(res => res.json());
Response headers now show:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Vary: Origin
Prevention
- Never use
*for origin when you need to support credentials. Always specify exact origins. - Set
credentials: truein the CORS configuration when cookies or Authorization headers are expected. - Add
Vary: Originso CDNs cache different responses for different origins correctly. - Use a whitelist function to dynamically determine the allowed origin at runtime for multi-domain support.
- Keep the frontend origin list in environment variables, not hardcoded.
- Remember that
withCredentialsforXMLHttpRequestandcredentials: 'include'for fetch behave the same way.
DodaTech Tools
Doda Browser blocks credentialed requests with wildcard CORS and logs a detailed explanation in the console. DodaZIP's security audit module scans API configurations for wildcard CORS settings and flags them as violations. Durga Antivirus Pro uses strict origin-plus-credentials CORS for all its cloud synchronization endpoints.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro