Auth with Bun
×


Auth with Bun

111

๐Ÿ” Introduction to Auth with Bun

Authentication is the backbone of any secure application โ€” whether it's a personal blog or a full-blown SaaS platform. If you're building your backend using Bun, the good news is: auth doesn't have to be complicated ๐Ÿš€.

In this blog, we'll explore how to implement authentication in Bun using simple techniques like sessions, tokens (JWT), and password hashing. Whether you're building a login form or an API gateway, this guide will help you lay a secure foundation.

๐Ÿง  Understanding the Basics of Auth

Before jumping into code, let's clarify what "auth" really means:

  • Authentication โžค Who are you?
  • Authorization โžค What are you allowed to do?

In this blog, weโ€™ll focus mainly on Authentication โ€” verifying user identity using email and password, and issuing secure tokens.

๐Ÿ› ๏ธ Setting Up a Basic Bun Server

Letโ€™s begin with a basic Bun server structure to handle login and protected routes:

const server = Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response("Hello from Bun Auth ๐Ÿ”");
  }
});

console.log("Server running at http://localhost:3000");

๐Ÿง‚ Hashing Passwords with Bun + bcrypt

Never store plain passwords โ€” hash them! Hereโ€™s how to hash and compare using bcrypt (or bcryptjs if you want full JS compatibility).

import bcrypt from "bcryptjs";

const password = "supersecret";

// Hash
const hashedPassword = await bcrypt.hash(password, 10);

// Verify
const isValid = await bcrypt.compare("supersecret", hashedPassword);
console.log("โœ… Password Match:", isValid);

Use this logic inside your registration and login handlers.

๐Ÿ”‘ Using JWT for Stateless Authentication

JWT (JSON Web Tokens) are perfect for token-based APIs. Here's how to issue and verify them using jsonwebtoken:

import jwt from "jsonwebtoken";

const user = { id: 123, email: "user@example.com" };

// Sign a token
const token = jwt.sign(user, "secretkey", { expiresIn: "1h" });

// Later, verify
const decoded = jwt.verify(token, "secretkey");
console.log("๐ŸŽŸ๏ธ Decoded Token:", decoded);

Store the token in cookies or headers and send it with each request to protect routes.

๐Ÿ” Protecting Routes with Middleware

Hereโ€™s how you can protect a route in Bun by checking for a valid JWT token:

function requireAuth(req) {
  const authHeader = req.headers.get("Authorization");
  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    return new Response("Unauthorized", { status: 401 });
  }

  const token = authHeader.split(" ")[1];

  try {
    const user = jwt.verify(token, "secretkey");
    return new Response(`Welcome back, ${user.email} ๐Ÿ‘‹`);
  } catch (err) {
    return new Response("Invalid token", { status: 403 });
  }
}

๐Ÿ“ฆ Sample Login Endpoint

Now letโ€™s wire up a complete login flow:

const users = [
  { email: "test@bun.dev", password: await bcrypt.hash("pass123", 10) }
];

const server = Bun.serve({
  port: 3000,
  async fetch(req) {
    if (req.url.endsWith("/login") && req.method === "POST") {
      const body = await req.json();
      const user = users.find(u => u.email === body.email);
      
      if (!user) return new Response("User not found", { status: 404 });
      
      const match = await bcrypt.compare(body.password, user.password);
      if (!match) return new Response("Wrong password", { status: 401 });

      const token = jwt.sign({ email: user.email }, "secretkey", { expiresIn: "1h" });
      return new Response(JSON.stringify({ token }), {
        headers: { "Content-Type": "application/json" }
      });
    }

    return new Response("404 Not Found", { status: 404 });
  }
});

๐Ÿช Token Storage Options: Cookies vs Headers

You can return the JWT in different ways:

  • HTTP-only cookies โ€“ great for browser security
  • Authorization headers โ€“ ideal for APIs and mobile clients

For secure web apps, use HTTP-only cookies to prevent token theft via XSS.

๐Ÿ”„ Logging Out Users

To log a user out, you can either:

  • Delete the cookie containing the token
  • Let the JWT expire (short lifespan)

You can also maintain a server-side blacklist if you need to revoke tokens manually.

๐Ÿง  Final Thoughts on Bun + Auth

Authentication in Bun is fast, flexible, and scalable. Thanks to its native TypeScript support and blazing performance, securing your routes and managing users is smooth and efficient.

Whether youโ€™re building session-based web apps or modern token-based APIs, Bun gives you the tools to implement secure authentication workflows without the bloat.



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