Handling CORS in Bun
0 108
🌐 Introduction to Handling CORS in Bun
When you're building APIs with Bun, one of the first issues you'll run into—especially in frontend-backend setups—is the dreaded CORS error 😵. Whether you're calling your Bun server from React, Vue, or any browser-based app, the browser enforces CORS (Cross-Origin Resource Sharing) rules to protect users.
In this guide, we’ll demystify CORS and show how to handle it gracefully in Bun, with real examples and practical techniques.
❓ What is CORS?
CORS is a browser security feature that restricts web pages from making requests to a different domain than the one that served the web page.
For example, if your frontend is running on http://localhost:3000
and your Bun server is on http://localhost:4000
, your browser will block requests unless the server explicitly allows it via CORS headers.
🚨 Common CORS Error Message
If your Bun server isn't configured for CORS, you might see this error:
Access to fetch at 'http://localhost:4000/api' from origin 'http://localhost:3000' has been blocked by CORS policy.
Don’t worry — it’s fixable. Let’s look at how.
🛡️ Basic CORS Headers in Bun
The key to handling CORS is setting the right headers. Here's how you can manually add them in a Bun server:
const server = Bun.serve({
port: 4000,
fetch(req) {
const headers = {
"Access-Control-Allow-Origin": "*", // or specific origin
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization"
};
// Handle preflight OPTIONS request
if (req.method === "OPTIONS") {
return new Response(null, { status: 204, headers });
}
return new Response("Hello CORS World 🌍", { headers });
}
});
This setup allows any origin to access your API. For production, replace *
with the actual domain.
🎯 Restricting to Specific Origins
For better security, don’t allow all origins. Here's how to whitelist a specific one:
const allowedOrigin = "http://localhost:3000";
const headers = {
"Access-Control-Allow-Origin": allowedOrigin,
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization"
};
You can even create a dynamic check if you expect multiple frontend environments.
⚙️ Handling Preflight Requests
Whenever your frontend sends a request with methods like PUT
or headers like Authorization
, the browser sends a preflight OPTIONS
request first.
If you don’t respond to this correctly, the browser will block the actual request. Always check for OPTIONS and return status 204:
if (req.method === "OPTIONS") {
return new Response(null, { status: 204, headers });
}
🧠 Making It Reusable: CORS Middleware
Let’s create a reusable function to inject CORS headers into any response:
function withCORS(response) {
response.headers.set("Access-Control-Allow-Origin", "*");
response.headers.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization");
return response;
}
And use it like this:
return withCORS(new Response("CORS OK ✅"));
🧪 Testing CORS with Fetch
From your frontend, test the Bun API with a fetch request:
fetch("http://localhost:4000/api", {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})
.then(res => res.text())
.then(console.log)
.catch(console.error);
If everything’s configured right, the request should go through smoothly.
🔐 Bonus: CORS + Authentication
When sending tokens or credentials, also handle Access-Control-Allow-Credentials
:
const headers = {
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET, POST",
"Access-Control-Allow-Headers": "Content-Type, Authorization"
};
Then in your frontend:
fetch("http://localhost:4000/protected", {
credentials: "include"
});
🏁 Wrapping Up
CORS doesn’t have to be a blocker when working with Bun. With the right headers and a bit of awareness around preflight requests, you can build secure and browser-friendly APIs in no time 🌈.
Use permissive headers in development and tighten them up for production. And if you’re building reusable Bun modules or APIs for public use — always set your CORS policies intentionally.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments