Auth with Bun
0 1521
🔠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 tutorial, 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 tutorial 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?
ðŸ› ï¸ 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 usingbcrypt (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 usingjsonwebtoken:
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
🔄 Logging Out Users
To log a user out, you can either:- Delete the cookie containing the token
- Let the JWT expire (short lifespan)
🧠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!
Share:



Comments
Waiting for your comments