Logo
Logo
Home
Archive
AI Agent Notes
Advertise
YouTube
Login
Sign Up
Logo
  • Home
  • Posts
  • 🦥 CORS: The Most Annoying Web Problem

🦥 CORS: The Most Annoying Web Problem

Mar 18, 2025

Sponsored by

Hello friends!

Welcome to this week’s Sloth Bytes. I hope you had a weird week 😉

Did you do me that favor?

If you already filled it out last week, you can uh… skip this and enjoy the today’s newsletter.

If you didn’t read last weeks Sloth bytes or skipped my welcome email… (why?)

I recently made a welcome survey for the newsletter.

The survey helps me improve the newsletter by knowing what programming languages you use, what areas you’re interested in, and how you learn.

It’s a very quick survey, it’ll only take 30 seconds.

It's just 8 quick questions about your programming experience, interests, and preferred learning formats. No essay questions, I promise!

Complete the Welcome Survey →

This will be the last week I mention it (Unless a lot of you skip it…)

There’s a reason 400,000 professionals read this daily.

Join The AI Report, trusted by 400,000+ professionals at Google, Microsoft, and OpenAI. Get daily insights, tools, and strategies to master practical AI skills that drive results.

Sign up now for free and work smarter, not harder.

CORS: The Most Annoying Web Problem

I remember when I first started learning full-stack development.

I was so excited to finally build both frontend and backend.

After tweaking my poorly made backend code, I finally had my API ready to test. Feeling confident, I fired up my frontend, made the call to amazing 10x developer API I crafted, and then BAM:

And that my friends… was my first encounter with CORS.

🧐 First things first: What exactly is CORS?

Cross-Origin Resource Sharing (CORS) is an HTTP-header mechanism that lets a server tell browsers which other origins are allowed to read its responses.

Think of it like an exclusive VIP list: your browser uses this list to decide if a website is allowed access to external resources.

Browsers enforce a security rule called the same-origin policy. Two URLs have the same origin only when their scheme (protocol), host, and port match.

  1. Same domain

  2. Same protocol

  3. Same port

If any of those differ, the URLs are cross-origin. Browser JavaScript is restricted from freely reading cross-origin responses unless the target server opts in through CORS. Important nuance: the browser may still send some cross-origin requests; the same-origin policy mainly restricts what scripts can read or access.

Quick same-origin policy example:

If your app runs at:

  • http://example.com:80

Here’s what happens if you try to make a request to these domains with same-origin policy active:

  • ✅ http://example.com:80/page.html (same origin)

  • ❌ https://example.com (different protocol)

  • ❌ http://example.com:3000 (different port)

  • ❌ http://otherdomain.com (different domain)

Yeah… it’s pretty picky (for good reason!)

🚧 Why does CORS exist?

The same-origin policy is a foundational browser security boundary that prevents a page on one origin from freely reading sensitive data from another origin. CORS does not replace that policy—it is a controlled way for servers to relax it.

Without that boundary, a malicious page could potentially read private responses from sites where you’re already authenticated. CSRF is a related but different problem: cross-origin requests can sometimes still be sent, which is why applications also use protections such as SameSite cookies and CSRF tokens.

So the mental model is: same-origin policy blocks cross-origin access by default; CORS headers selectively grant browser scripts permission to read specific cross-origin responses.

⚙️ How does CORS work?

I’ll be taking this example straight from AWS article on CORS

Let’s say we have a website called: news.example.com.

This site wants to access resources from an API at partner-api.com.

Developers at partner-api.com need to configure CORS headers on their server by adding:

Access-Control-Allow-Origin: https://news.example.com

This sets up CORS so that news.example.com can ask for resources from partner-api.com.

When partner-api.com responds, the browser checks its CORS response headers. For example, the server can return:

Access-Control-Allow-Origin: https://news.example.com

That tells the browser that scripts from https://news.example.com may read the response. If the request includes credentials such as cookies, the server must also explicitly opt in with Access-Control-Allow-Credentials: true, and the client must send the request with credentials enabled.

Access-Control-Allow-Origin normally contains one allowed origin or the wildcard *. If you support several origins, your server typically checks the incoming Origin header against an allowlist and echoes the matching origin. You cannot put multiple origins in a comma-separated Access-Control-Allow-Origin value.

Access-Control-Allow-Origin: *

The wildcard is useful for public, non-credentialed resources. You cannot use * as the allowed origin for a credentialed CORS request.

🚩 Preflight requests for complex HTTP calls

Some requests trigger an extra security check called a preflight request.

This happens if:

  • You’re using methods like PUT, PATCH, DELETE

  • Custom headers or certain content-types are involved.

How To Handle CORS

CORS is pretty easy to handle with modern day programming languages/tools.

They usually have a built in/community maintained package that lets you set it up easily:

JavaScript (Express + Node)

const express = require('express');
//You can install this with npm install cors
const cors = require('cors');
const app = express();

app.use(cors({
  origin: 'http://localhost:3000', // specific origin or '*' for all
  methods: 'GET,POST,PUT,DELETE',
  credentials: true
}));

app.listen(3001, () => console.log('Server running on port 3001'));

Python (Flask)

from flask import Flask
# Install with: pip install flask-cors
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}})

@app.route('/api/data')
def data():
    return {"message": "Hello, CORS"}

app.run(port=5000)

Fun fact: WebSockets use a different protocol after the HTTP upgrade, so the browser’s CORS algorithm does not apply to WebSocket messages in the same way. But origin security still matters: browsers send an Origin header during the handshake, and WebSocket servers should validate it when appropriate.

Next time CORS tries to ruin your day, just smile and handle it like the coding champ you are.

If you want to learn more about CORS, then check out the mdn docs here.

If you want to keep learning

  • APIs explained — the request/response foundation behind most CORS problems you’ll actually encounter.

  • Web frameworks explained — how frameworks structure frontend/backend communication and often provide CORS configuration for you.

  • WebSockets explained — real-time browser communication has a different connection model, but origin and security boundaries still matter.

Sloths have the slowest metabolic rate of any non-hibernating land mammal.

Giphy

Nvidia GTC is happening!

GTC, Nvidia’s biggest conference of the year, starts this week in San Jose.

Discord launches SDK to help developers enhance social experiences in their games (2 minute read)

Discord on Monday announced the launch of its Discord Social SDK, a free toolkit for developers to enhance their games.

Google announces Gemini Robotics for building general purpose robots  (2 minute read)

Google DeepMind announced Gemini Robotics to bring “AI into the physical world.”

A Software Engineer's Guide to Reading Research Papers (11 minute read)

My personal framework for reading research papers.

As an engineer, I’d rather be called stupid than stay silent (8 minute read)

This is how you can overcome imposter syndrome in tech - by embracing vulnerability and asking questions.

Thank you to everyone who submitted! A LOT of you submitted this week 😁

ShadowDara, papu163, RelyingEarth87, JamesHarryT, ravener, ghostgamr, Repr-dev, Raufirzaman, Franspi-lol, Pennicillina, Dhwani1401, Dhwani1401, josericardo-fo, FredericoSRamos, aviral-trivedi, JustVal-su, maxwellnewage, Gilymiona, bakzkndd, mlobermeier, GabrielDornelas, and HighlandCuwu.

Bridge Shuffle

Create a function to bridge shuffle two arrays.

To bridge shuffle, you interleave the elements from both arrays in an alternating fashion:

array1 = ["A", "A", "A"]
array2 = ["B", "B", "B"]

shuffled_array = ["A", "B", "A", "B", "A", "B"]

This can still work with two arrays of uneven length. We simply tack on the extra elements from the longer array:

array1 = ["C", "C", "C", "C"]
array2 = ["D"]

shuffled_array = ["C", "D", "C", "C", "C"]

Examples

bridgeShuffle(["A", "A", "A"], ["B", "B", "B"])
output = ["A", "B", "A", "B", "A", "B"]

bridgeShuffle(["C", "C", "C", "C"], ["D"])
output = ["C", "D", "C", "C", "C"]

bridgeShuffle([1, 3, 5, 7], [2, 4, 6])
output = [1, 2, 3, 4, 5, 6, 7]

Notes

  • Elements in both arrays can be strings or integers.

  • If two arrays are of unequal length, add the additional elements of the longer array to the end of the shuffled array.

  • Always start your shuffle with the first element of Array 1.

How To Submit Answers

Reply with

  • A link to your solution (github, twitter, personal blog, portfolio, replit, etc)

  • or if you’re on the web version leave a comment!

  • If you want to be mentioned here, I’d prefer if you sent a GitHub link or Replit!

Still working on those 2 videos… yes I’m slow

What did you expect?

That’s all from me!

Have a great week, be safe, make good choices, and have fun coding.

If I made a mistake or you have any questions, feel free to comment below or reply to the email!

See you all next week.

What'd you think of today's email?

  • 🦥 Amazing! Keep it up
  • 🦥 Good, not great
  • 🦥 It sucked

Login or Subscribe to participate

Want to advertise in Sloth Bytes?

If your company is interested in reaching an audience of developers and programming enthusiasts, you may want to advertise with us here.

Keep Reading

Read all
arrow-right
envelope-simple

Join 50k+ developers and become a better programmer and stay up to date in just 5 minutes.

© 2026 Sloth Bytes.
beehiivPowered by beehiiv