Input Validation in Bun
0 106
๐งน 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
Use escaping libraries or ORMs with built-in sanitization, and never trust unchecked input from the client, even if it "looks safe" ๐งฏ.
๐ฌ 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