Bun + SQLite Setup
×


Bun + SQLite Setup

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 and ON 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!



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