Response Handling Techniques
0 118
๐ฆ Response Handling Techniques: Mastering API Communication
Handling responses properly is one of the most overlooked aspects of backend development, yet it's absolutely crucial. Whether you're building an API with Bun.js, Node.js, or any modern backend stack, understanding Response Handling Techniques ensures you deliver the right message, at the right time, in the right format.
๐จ What is Response Handling?
Response handling is the process of managing how your server replies to incoming HTTP requests. This includes setting status codes, defining headers, formatting the body (e.g., JSON, text, HTML), and structuring error messages. Itโs the final handshake your API makes with the client.
๐ก Key Elements of a Proper Response
- Status Code โ Indicates the result (e.g., 200 OK, 404 Not Found, 500 Internal Server Error)
- Headers โ Meta-data about the response (e.g., Content-Type, Cache-Control)
- Body โ The actual data sent back, usually in JSON
๐ Basic Response in Bun.js
Hereโs a simple example of how to return a response in Bun:
// server.ts
Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello from Bun!", {
headers: { "Content-Type": "text/plain" },
status: 200
});
}
});
This example sends a plain text response with a 200 status code.
๐ก Use JSON for APIs
In APIs, JSON is the most common response format. Hereโs how you can send a structured JSON response:
const data = { message: "Success", status: "ok" };
return new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" },
status: 200
});
This ensures clients can easily parse and use the response data.
โ ๏ธ Error Handling Best Practices
When something goes wrong, send the correct HTTP error code along with a helpful message:
const error = { error: "User not found" };
return new Response(JSON.stringify(error), {
headers: { "Content-Type": "application/json" },
status: 404
});
Use appropriate status codes to communicate clearly:
- 400 โ Bad Request
- 401 โ Unauthorized
- 403 โ Forbidden
- 404 โ Not Found
- 500 โ Internal Server Error
๐ฏ Custom Headers for Better Control
Adding headers improves interoperability and control. For example, controlling CORS:
return new Response(JSON.stringify({ msg: "Done" }), {
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
status: 200
});
๐ Redirecting Requests
You can use status codes like 301 or 302 to redirect users:
return new Response(null, {
status: 302,
headers: {
"Location": "https://yourdomain.com/new-page"
}
});
๐ Secure Response Headers
Enhance your APIโs security by setting proper headers:
headers: {
"Content-Type": "application/json",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "no-referrer"
}
These headers help prevent common attacks like clickjacking and MIME type sniffing.
โฑ๏ธ Response Time Optimization
Speed matters. Some tips:
- Compress large responses using
gzip
- Only send necessary data (avoid bloated objects)
- Use caching headers like
Cache-Control
for static content
๐ฆ Sending Files or Buffers
Need to return an image or PDF? Here's how to send binary data:
const file = await Bun.file("./image.jpg").arrayBuffer();
return new Response(file, {
headers: { "Content-Type": "image/jpeg" },
status: 200
});
๐งช Consistency in Response Structure
Always maintain a consistent structure in your API responses. This improves developer experience and allows clients to build robust integrations.
{
"status": "success",
"data": {
"user": {
"id": 1,
"name": "Alice"
}
},
"message": "User fetched successfully"
}
โ Wrapping Up
Mastering Response Handling Techniques is key to building professional-grade APIs. From setting status codes to crafting secure headers and optimizing for performance, the way you handle responses directly impacts the experience of the end-user.
With Bun.js or any other backend framework, nailing your responses means more reliable apps and happier developers on the receiving end.
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