DEV Community

Tejaswa Hinduja
Tejaswa Hinduja

Posted on

What is CORS?

So while building full stack projects , I came across this annoying thing called cors, whenever I tried to send a request from my frontend to the backend it never went through and it was pretty frustrating.So here's my attempt to explain it to someone who is just starting out building projects.

In almost all of the full stack projects you would come across there are two things interacting with each other,the client and the server,For example


Now lets say you have two tabs open in a browser,
1.tejaswahinduja.me
2.Instagram.com
both of the sites would have their own servers
and you are logged into instagram and you now visit tejaswahinduja.me,Lets say I have added some js code on my client side like fetch(instagram/user/inbox/chats) this will send a request to the instagram's server and since you are already logged in your cookies exist, through which the instagram's server can validate that you are logged in and it would return the response,You can now figure out whats wrong here right, tejaswahinduja.me shouldn't be able to access your insta account.To prevent this,The same-origin-policy is a critical security mechanism that restricts how a script loaded from a origin interact with other origins.But now you cannot interact with your frontend and backend since they are two different origins.
**Now how does CORS(cross origin resource sharing) helps in solving this?
First lets see ,What is a origin?A origin is nothing but a tuple of:-scheme(http/https)+host+port for eg:https://tejaswahinduja.me and https://www.tejaswahinduja.me are two different origins.
CORS is an HTTP-header based mechanism that allows a server to indicate any origins other than its own from which a browser should permit loading resources.In short the backend can decide which client to trust and who not to.How this works it lets the server decide which origins to permit, check the below image.

The server sends a Access-Control-Allow-Origin in the response headers which tells the broswer if the client is allowed or not.By default the cookies are not sent to the server so credentials:include is used to send the cookies to the server.
Well this works perfectly fine when making standard http requests like get and post.
But if the client makes a non-standard http requests like put,delete,etc the browser then first sends a "preflight" request which just checks if the origin is allowed or not.If the origin is not allowed then a CORS error occurs.
That’s CORS in action strict, sometimes frustrating, but essential for web security.

If you liked the blog, lets connect
Twitter:https://x.com/Tej_Codes
Linkedin:https://www.linkedin.com/in/tejaswa-hinduja-b585b6323/
Github:https://github.com/TejaswaHinduja

Sources:-
https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS
https://www.youtube.com/watch?v=WWnR4xptSRk

Top comments (0)