what’s CORS

tags: learning networking

content

CORS

  • Cross Origin Resource Sharing
  • it’s a browser security mechanism
  • an origin is protocol + domain + port

Note

Important: it’s the browser, not the server, enforcing CORS

scenario:

  • simple web app
    • frontend: localhost:5173
    • backend: localhost:8080
  • when browser needs frontend static files, requests are sent to localhost:5173
  • web server returns static files (e.g., coffee.js)
  • coffee.js wants to requests localhost:8080/coffees
  • when browser is about to execute this api to localhost:8080, it stops
    • because these are different origins
      • coffee.js is from localhost:5173
      • coffee.js wants to request localhost:8080

with nginx

  • browser executes javascript coffee.js (from localhost:5173)
  • coffee.js wants to get coffees resource
    • instead of localhost:8080
    • request is sent to http://localhost:5173/api/...
  • nginx redirects /api/ traffic to http://localhost:8080
  • backend is listening on 8080, backend receives request

Note

before nginx, browser requests to frontend and backend are different.

  • localhost:5173 and localhost:8080
  • browser stops this, because they are different origins

with nginx, browser requests are only sent to localhost

up

down

reference