Bun + SQLite Setup
0 107
๐ Introduction to Bun + SQLite
Combining Bun โ the ultra-fast JavaScript runtime โ with SQLite โ a lightweight and file-based SQL database โ gives you a powerful backend stack that's fast, portable, and efficient. Whether you're building a local API, CLI tool, or lightweight server, this combo is ideal for quick data persistence without spinning up an external DB server.
โ๏ธ Why Bun + SQLite?
- ๐ Blazing speed: Bun executes JavaScript faster than Node and supports native bindings.
- ๐ No server required: SQLite is just a file. No need to install or run a separate service.
- ๐ฆ Zero-config storage: Drop in a DB file and start reading/writing immediately.
- ๐ง Perfect for small projects, prototyping, or embedded apps.
๐ฆ Installing Required Packages
Letโs start by initializing your Bun project and adding SQLite support:
bun init
bun add better-sqlite3
Weโre using better-sqlite3
, a blazing fast, synchronous SQLite client that works beautifully with Bun.
๐ Setting Up the Database File
Letโs create a file called db.ts
to handle our SQLite connection.
// db.ts
import Database from 'better-sqlite3';
const db = new Database('app.db'); // this creates 'app.db' if it doesn't exist
// Create a table
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
);
`);
export default db;
Thatโs it โ your database and user table are ready to go!
๐ Inserting and Querying Data
Now let's create a simple file to insert a user and fetch all users:
// user-service.ts
import db from './db.ts';
const insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)');
insert.run('Aditya', 'aditya@example.com');
const getAll = db.prepare('SELECT * FROM users');
const users = getAll.all();
console.log("๐ฅ All Users:", users);
This example demonstrates synchronous inserts and selects, perfect for command-line tools, small APIs, or scripting tasks.
๐ Updating and Deleting Records
// Update user
const update = db.prepare('UPDATE users SET name = ? WHERE id = ?');
update.run('Adi', 1);
// Delete user
const del = db.prepare('DELETE FROM users WHERE id = ?');
del.run(1);
Each of these operations runs instantly and safely thanks to SQLite's atomic design.
๐ Directory Structure Overview
my-bun-sqlite-app/
โโโ db.ts
โโโ user-service.ts
โโโ app.db # SQLite DB file (auto-created)
โโโ bun.lockb
โโโ package.json
๐ก Pro Tips for SQLite with Bun
- ๐งช Use transactions: Wrap batch operations in
db.transaction()
for performance and atomicity. - ๐ Handle constraints: Use
IF NOT EXISTS
andON CONFLICT
clauses wisely. - ๐ฆ Validation: Validate input manually or with a schema library (e.g., zod) before inserting.
๐ก Creating a Simple Bun Server with SQLite
Letโs expose our SQLite queries via a simple HTTP server using Bunโs built-in APIs:
// index.ts
import db from './db.ts';
const handler = () => {
const stmt = db.prepare('SELECT * FROM users');
const users = stmt.all();
return new Response(JSON.stringify(users), {
headers: { 'Content-Type': 'application/json' }
});
};
Bun.serve({
port: 3000,
fetch: handler,
});
console.log("๐ Server running at http://localhost:3000");
๐งต Is This Production Ready?
SQLite is a great choice for local dev, small-scale apps, or internal tools. For larger-scale apps with concurrent writes, you might want to explore external DBs. But for MVPs and quick bootstrapped backends, Bun + SQLite is a dream combo.
๐งพ Final Thoughts
Setting up Bun + SQLite is simple, fast, and powerful. Whether youโre building microservices, automation scripts, or prototypes, this pairing gives you database-backed logic in minutes without any extra infrastructure.
So next time you want a backend without the bloat, just Bun it and let SQLite handle the rest. โก๐
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