We earn commission when you buy through affiliate links.

This does not influence our reviews or recommendations.Learn more.

Nowadays, backend servers and frontend clients are deployed on different domains.

CORS-simple request flow tells that it sends a cross-origin request but when it received response. It checks for headers.

Therefore the server has to enable CORS to allow clients to communicate with the server on browsers.

Also, servers are implementing stateless authentication for better scalability.

Tokens are stored and maintained on the client-side, but not on the server side like session.

CORS-Preflight Request Image which show the flow of cross-origin request with OPTIONS preflight request before sending actual request for verifying headers.

For security, its better to store tokens in HTTPOnly cookies.

Why are Cross-Origin requests blocked?

Lets assume that our frontend utility deployed athttps://app.geekflare.com.

A script loaded inhttps://app.geekflare.comcan only request same-origin resources.

Its actually for security to protect users from attacks like CSRF(Cross-Site Request Forgery).

Attackers can easily send their malicious pagehttps://malicious.com/transfer-money-to-attacker-account-from-user-paypal-accountby converting it to short-URL to hide the actual URL.

Anyone can easily steal money without a PayPal account user knowledge.

For the above reason, browsers block all the cross-origin requests.

What is CORS(Cross-Origin Resource Sharing)?

How CORS works?

As the server already defined its trusted domain in its CORS configuration.

But it is not safe unless you need it.

How to enable CORS?

For enabling CORS in apache and Nginx webserver, follow thistutorial.

But for enabling specific methods(GET, POST, PUT).

Used to allow headers other than defaults to send with actual requests.

To intimate the web app to cache the preflight response information in the cache for a specified second.

Omit this if you dont want to cache the response.

The cached preflight response will be available for 10 mins in the online window.

A cookie is a small piece of data that the server will send to the client surfing app.

Cookie has its attribute, which can be defined to make a cookie work differently as we need.

Suppose if any one of your pages is weak to an XSS attack.

Attackers may misuse user tokens stored in the net online gate.

HTTPOnly cookies are only set/get by server/backend but not on the client-side.

Client-side script restricted to access that HTTPonly cookie.

So HTTPOnly cookies are not vulnerable to XSS Attacks and are more secure.

Because its only accessible by the server.

Lets see an example code that sets an access token in HTTPOnly cookie after checking the login credentials.

you could follow thistutorialfor apache and Nginx for enabling CORS by following the above steps.

Why storing cookies in HTTPOnly is secure and how withCredentials used in clients for cross-origin requests.