Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท File I/O, SQLite and Data

Passwords, Hashing, Environment and Other Data Clients

Hash passwords with Bun.password, compute digests with CryptoHasher, load .env files and Bun.env, compress data, and meet Bun's built-in Postgres, Redis and S3 clients.

Beyond files and SQLite, Bun bundles the helpers that most backends need: password hashing, general hashing, environment configuration, compression, and clients for popular data services. This lesson tours them with a focus on doing each one safely.

Bun is not available here, so Bun-specific calls are read-only. Runnable blocks use Node 24 equivalents (crypto.scrypt, crypto.createHash, zlib) to show the concepts. They are stand-ins and do not produce Bun's exact outputs.

Password hashing with Bun.password

Never store passwords as plain text, and never use a fast hash such as SHA-256 for them. A password hash must be slow on purpose and salted (a random value mixed in, so equal passwords produce different hashes). Bun has this built in:

TypeScript
const hash = await Bun.password.hash("correct horse battery staple");
// "$argon2id$v=19$m=65536,t=2,p=1$....": algorithm, cost and salt are inside the string

const ok = await Bun.password.verify("correct horse battery staple", hash);   // true
const bad = await Bun.password.verify("wrong guess", hash);                     // false

The default algorithm is argon2id, a modern memory-hard design. You can choose bcrypt and tune cost:

TypeScript
await Bun.password.hash(password, { algorithm: "argon2id", memoryCost: 65536, timeCost: 2 });
await Bun.password.hash(password, { algorithm: "bcrypt", cost: 12 });

Because the settings and salt are stored inside the hash string, verify needs only the password and the stored string, and old hashes keep working when you raise the cost later. Save the whole string in one database column. There are synchronous versions (hashSync, verifySync) but the async ones run off the main thread, so a login burst does not freeze the server.

A login route in outline:

TypeScript
POST: async (req) => {
  const { email, password } = await req.json();
  const user = db.query("SELECT id, password_hash FROM users WHERE email = ?").get(email);
  const valid = user && (await Bun.password.verify(password, user.password_hash));
  if (!valid) return Response.json({ error: "Invalid credentials" }, { status: 401 });
  // create a session...
}

Return the same message for "unknown email" and "wrong password" so attackers cannot discover which accounts exist, and rate-limit the endpoint.

Node.js Salted, slow hashing (Node scrypt stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Fast hashing and digests

For checksums, cache keys and signatures, use fast hashes. Bun.CryptoHasher supports the common algorithms (sha256, sha512, md5, blake2b256, and more), and Bun.hash offers very fast non-cryptographic hashes:

TypeScript
const digest = new Bun.CryptoHasher("sha256").update("hello").digest("hex");
// 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

const hmac = new Bun.CryptoHasher("sha256", "secret-key").update("message").digest("hex");

console.log(Bun.hash("hello"));        // fast 64-bit number: hash tables, ETags, sharding
console.log(crypto.randomUUID());      // random v4 id (Web Crypto)
console.log(Bun.randomUUIDv7());       // time-ordered id, nicer as a database key

Rule of thumb: passwords use Bun.password; integrity and signatures use CryptoHasher/HMAC; speed-only purposes with no attacker use Bun.hash. md5 and sha1 are fine for non-security checksums only. crypto.getRandomValues and crypto.subtle from Web Crypto are available too, for AES, RSA and ECDSA.

Node.js Digests and HMAC with node:crypto

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Environment variables and .env files

Configuration (ports, API keys, database URLs) belongs in the environment, not in code. Bun reads .env files automatically, with no dotenv package:

TEXT
# .env
PORT=4000
DATABASE_URL=sqlite://./app.db
API_KEY=dev-key-123
TypeScript
console.log(Bun.env.PORT);          // "4000": same object as process.env
console.log(process.env.API_KEY);   // also works
const port = Number(Bun.env.PORT ?? 3000);

Load order (later wins): .env, then .env.production / .env.development / .env.test depending on NODE_ENV, then .env.local (not read when NODE_ENV=test), then real environment variables from your shell, which always win. Values may reference others (URL=http://localhost:$PORT). Values are always strings: convert them and fail fast when something required is missing:

TypeScript
function requireEnv(name: string): string {
  const value = Bun.env[name];
  if (!value) throw new Error(`Missing environment variable ${name}`);
  return value;
}
const apiKey = requireEnv("API_KEY");

Add .env and .env.local to .gitignore; commit a .env.example with fake values. Use bun --env-file=.env.staging run app.ts to pick a file by hand, and --no-env-file-style options when you do not want automatic loading.

Compression

Bun has fast built-in compression:

TypeScript
const data = new TextEncoder().encode("a".repeat(10_000));
const gz = Bun.gzipSync(data);            // Uint8Array
const back = Bun.gunzipSync(gz);
console.log(data.length, "->", gz.length); // 10000 -> tiny
// also: Bun.deflateSync / inflateSync, and Bun.zstdCompress (zstd) in newer versions

HTTP servers can compress responses by checking Accept-Encoding and sending Content-Encoding: gzip, but in production a reverse proxy usually does this for you.

Node.js gzip with node:zlib

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Built-in clients for databases and storage

Recent Bun versions bundle drivers, so common services need no npm package. Treat these as read-only examples and check the documentation of your installed version for details:

TypeScript
// PostgreSQL (also MySQL and SQLite through the same tagged-template API)
import { sql } from "bun";
const users = await sql`SELECT id, name FROM users WHERE active = ${true} LIMIT ${10}`;
// values in ${} are sent as parameters, never pasted into the SQL text

// Redis
import { redis } from "bun";
await redis.set("greeting", "hello");
console.log(await redis.get("greeting"));
await redis.incr("visits");

// S3-compatible object storage (AWS, Cloudflare R2, MinIO, ...)
import { s3 } from "bun";
const file = s3.file("reports/2026-q1.pdf");
await file.write(await Bun.file("./q1.pdf").bytes());
const url = file.presign({ expiresIn: 3600 }); // temporary download link

These clients read connection details from environment variables such as DATABASE_URL, REDIS_URL and S3_BUCKET unless you pass them explicitly. The sql tagged template is safe against injection because interpolated values become query parameters, the same principle as in bun:sqlite.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why are salted slow hashes (argon2id, bcrypt) used for passwords instead of SHA-256?

    Passwords are low-entropy secrets, so the hash must be costly to compute and unique per user.
  2. 2. What does Bun.password.verify(password, hash) need besides the password?

    The encoded hash string carries everything needed to verify.
  3. 3. Which source wins when the same variable is set in .env and in the shell?

    Variables already in the process environment override values from .env files.
  4. 4. Which tool fits computing an HMAC signature?

    new Bun.CryptoHasher('sha256', key) computes keyed hashes; Bun.hash is non-cryptographic.

Summary

  • Bun.password.hash/verify (argon2id by default, bcrypt optional) is the right way to store passwords.
  • Bun.CryptoHasher for digests and HMAC; Bun.hash for fast non-security hashing; UUIDv7 for ordered ids.
  • .env files load automatically into Bun.env/process.env; values are strings; validate required ones; keep secrets out of git.
  • Bun.gzipSync and friends compress data.
  • Bun bundles sql, redis and s3 clients; interpolated values are parameters.

Next: Node.js Compatibility and Migrating a Project