Input Validation in Bun
×


Input Validation in Bun

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!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat