Auth with Bun
0 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!

Share:
Comments
Waiting for your comments