Sikau

Web essentials · Day 14 · about 30 min

HTTPS, CORS and safe redirects

Who can talk to whom, and how safely.

The rules of the road

Browsers protect people with a few strict rules: pages from one site can't freely read another site's data (the same-origin policy), servers can relax that on purpose (CORS), and everything should travel over HTTPS. Knowing these turns confusing errors into simple fixes.

Origins, CORS and redirects

  • An origin is protocol + host + port: https://sikau.app and https://api.sikau.app are different origins.
  • fetch to another origin is blocked from reading the response unless that server sends Access-Control-Allow-Origin allowing you. A CORS error is fixed on the server, not in your fetch.
  • HTTPS encrypts traffic and proves the site is who it says it is. Modern features (service workers, geolocation, clipboard) require it.
  • Open redirects: a login page that sends users to ?next= anywhere can be abused for phishing. Only allow redirects to your own origin.
  • Passwords are never stored as-is: servers keep a slow, salted hash (bcrypt, Argon2).
const a = new URL("https://sikau.app/courses");
const b = new URL("https://api.sikau.app/users");
const c = new URL("http://sikau.app/courses");
console.log(a.origin === b.origin, a.origin === c.origin);
console.log(new URL("/profile", a).origin === a.origin);

The rest of this lesson

  • Why the same-origin policy existsexplain
  • HTTPS and safe redirectsexplain
  • Same origin?predict
  • Protocol-relative trickpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 16 lessons of Web essentials