November 14, 2024

How to Use Drizzle ORM With SvelteKit

How to Use Drizzle ORM With SvelteKit

If you want to make your SvelteKit apps better with strong database management, you’re in the right place. Integrating Drizzle ORM with SvelteKit helps you manage databases efficiently while using the power of SQLite/Postgres/MySQL.

Why Use Drizzle ORM?

Drizzle ORM is a powerful, type-safe way to interact with your database. It works well with TypeScript, making it a good fit for SvelteKit apps, keeping your queries safe from runtime errors and boosting developer efficiency.

Setting Up Your SvelteKit Project

If you haven’t done it yet, create a new SvelteKit project by running:

bunx sv create your-app-name

Then, go to your project directory:

cd your-app-name

Install Drizzle ORM and SQLite

Next, install Drizzle ORM and SQLite. We will use Turso with libSQL, which is highly recommended. You can do that by running:

bun i drizzle-orm @libsql/client
bun i -D drizzle-kit

Configuring Drizzle ORM

You need to set up Drizzle ORM. Create a new file in your project for database configuration, like src/lib/db.ts:

import * as schema from "$lib/schema";
import { env } from "$env/dynamic/private";
import { createClient } from "@libsql/client";
import { drizzle } from "drizzle-orm/libsql";
import { migrate } from "drizzle-orm/libsql/migrator";

// Create database
const config = {
  url: env.TURSO_DATABASE_URL ?? "file:database.db",
  authToken: env.TURSO_AUTH_TOKEN,
};
const client = createClient(config);
export const db = drizzle(client, { schema });

// Optimize database
if (config.url.startsWith("file:")) {
  await db.run(`
    PRAGMA journal_mode = WAL;
    PRAGMA synchronous = NORMAL;
    PRAGMA busy_timeout = 5000;
    PRAGMA cache_size = 1000000000;
    PRAGMA foreign_keys = true;
    PRAGMA temp_store = memory;
  `);
}

// Run migrations when developing automatically
await migrate(db, { migrationsFolder: "migrations" });

This configuration sets up a basic connection to an SQLite database. You can define your table schemas using Drizzle ORM’s powerful features. You also want to set up drizzle.config.ts which is in the root of your project:

import { type Config } from "drizzle-kit";

export default {
  dialect: "turso",
  out: "./migrations",
  schema: "./src/lib/schema.ts",
  dbCredentials: {
    url: process.env.TURSO_DATABASE_URL ?? "file:database.db",
    authToken: process.env.TURSO_AUTH_TOKEN,
  },
} satisfies Config;

Defining Your Tables

The next step is to create your tables. For example, you might want to create a “users” table. Create a new file src/lib/schema.ts:

import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";

export const usersTable = sqliteTable("users", {
  id: integer("id").primaryKey(),
  name: text("name").notNull(),
  email: text("email").notNull(),
});

With your table defined, you can now use the database in your code. Let’s say you want to create a new user in a form action. That would look like this:

import { z } from "zod";
import { zod } from "sveltekit-superforms/adapters";
import { fail, superValidate } from "sveltekit-superforms";
import { db } from "$lib/db";
import { usersTable } from "$lib/schema";
import type { Actions, PageServerLoad } from "./$types";

const schema = z.object({
  name: z.string(),
  email: z.string().email(),
});

export const load: PageServerLoad = async () => {
  // Initialize form
  return {
    form: await superValidate(zod(schema)),
  };
};

export const actions: Actions = {
  default: async ({ request }) => {
    // Validate form
    const form = await superValidate(request, zod(form));
    if (!form.valid) return fail(400, { form });
    const { name, email } = form.data;

    // Insert into database
    await db.insert(usersTable).values({ name, email });
  },
};

This also uses Zod with Superforms to automatically validate the form properly. For more operations, check out the Drizzle ORM documentation.

Conclusion

Integrating Drizzle ORM with SvelteKit not only makes your database tasks simpler but also improves your app’s structure and consistency. With the combination of SQLite, Drizzle ORM, and TailwindCSS, you can build efficient, stylish apps that scale.

Start coding, and enjoy crafting your powerful SvelteKit app with seamless database integration!

🦀 Svelte + Rust = Mind-Blowing Speed! 🚀

Join my newsletter so you don't miss out on future updates!