What is Fetch API?
The Fetch API introduces the new fetch() method, which allows network requests to be made similarly to the XHR (XMLHttpRequest) method but more powerfully and flexibly. The Fetch API offers better performance than XMLHttpRequest and is easier to integrate with other technologies, such as Service Workers. The primary difference between the Fetch API and XMLHttpRequest is that Fetch uses promises, which allows you to have a cleaner and straightforward API without nested callbacks.
What are Credentials?
The credentials are cookies, authorization headers, and TLS client certificates that clients acquire from services or users for future authentication. The credentials used in authentication are digital documents that provide evidence of a user's identity, such as a certificate or password.
JavaScript Fetch with Credentials Examples
The following are examples of using the fetch() method with credentials in JavaScript:
Sending Credentials using the Fetch
To send a credential to the server, you must explicitly set the «credential: 'include'» parameter when calling the fetch() method. This will tell the browser to send credentials for both: same-origin and cross-origin calls. The following is an example of sending credentials using fetch() in JavaScript:
If the server rightly processes the request with credentials, it will send two CORS headers in response: "Access-Control-Allow-Credentials: true" and "Access-Control-Allow-Origin: https://reqbin.com".
Sending Credentials to Source Domain using the Fetch
To send credentials only to the origin domain (the URL is in the same origin as the calling script), you need to use the «credentials: 'same-origin'» parameter. The following is an example of sending credentials to the origin domain using fetch() in JavaScript:
How to prevent the browser from sending credentials?
To prevent the browser from sending and receiving credentials, use the «credentials: 'omit» parameter when calling the fetch() method: