Input Validation in Bun
0 718
🧹 Input Validation in Bun
User input is often unpredictable — and that's exactly why input validation is a non-negotiable part of every web application. Whether you're building REST APIs or WebSocket endpoints using Bun, ensuring that only valid, clean data enters your system protects you from bugs, crashes, and security issues ðŸ”.â“ Why Input Validation Matters
Bad input leads to bad output. Here's why validation should be your first line of defense:- 🚫 Prevents malformed data from breaking your logic
- ðŸ›¡ï¸ Blocks malicious attempts like SQL injection or XSS
- 💡 Provides helpful feedback to clients
- 📊 Keeps your database consistent and clean
âš™ï¸ Validating Input in Bun APIs
Let’s say you’re building a POST endpoint that receives user data like name and age. Here’s how to validate it:Bun.serve({
port: 3000,
async fetch(req) {
if (req.method === "POST" && new URL(req.url).pathname === "/register") {
const body = await req.json();
const { name, age } = body;
if (typeof name !== "string" || name.length < 2) {
return new Response("⌠Invalid name", { status: 400 });
}
if (typeof age !== "number" || age < 0 || age > 120) {
return new Response("⌠Invalid age", { status: 400 });
}
return new Response("✅ User data is valid!");
}
return new Response("Not Found", { status: 404 });
}
});
This simple check ensures that:
- 🔤 name is a string with at least 2 characters
- 🔢 age is a number within a reasonable range
🧰 Using Zod for Schema Validation
Instead of manually checking every field, you can use libraries like Zod for cleaner validation using schemas.import { z } from "zod";
const UserSchema = z.object({
name: z.string().min(2),
age: z.number().min(0).max(120)
});
Bun.serve({
port: 3000,
async fetch(req) {
const body = await req.json();
const result = UserSchema.safeParse(body);
if (!result.success) {
return new Response("⌠Invalid input: " + JSON.stringify(result.error.issues), { status: 400 });
}
return new Response("✅ Valid input received");
}
});
Using Zod makes the code more expressive and less error-prone — perfect for production-grade APIs 🚀.
ðŸ› ï¸ Validating Query Parameters
Don't forget to validate input from URL query strings too! Here’s how:Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
const page = url.searchParams.get("page");
if (!page || isNaN(Number(page))) {
return new Response("⌠'page' must be a number", { status: 400 });
}
return new Response(`📄 Loading page ${page}`);
}
});
🔠Protecting Against Injection Attacks
Always sanitize inputs — especially if they’re going to be used in:- 💾 Database queries
- ðŸ–¥ï¸ Command-line operations
- 🧩 HTML/JS rendering
📬 Custom Error Messaging
Make your validation feedback user-friendly:return new Response(JSON.stringify({
error: true,
message: "Age must be between 0 and 120"
}), {
status: 400,
headers: { "Content-Type": "application/json" }
});
This makes it easier for frontend devs (or API consumers) to handle errors properly ✨.
🧪 Test Your Validation Logic
Don’t stop at writing validation — test it!- ✅ Test for valid and invalid cases
- 💥 Simulate edge cases (empty strings, nulls, booleans, etc.)
- 🛠Log or trace failed validation attempts
ðŸ Final Thoughts
Input validation in Bun is critical for building secure and stable web applications. Whether you’re writing manual checks or using schema libraries like Zod, never let unsafe data sneak through. Clean input = clean logic 🧼.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