SQLite

SQLite 是一个轻量级、无服务器、独立的 SQL 数据库引擎,广泛用于应用中的本地数据存储。 在这里阅读更多内容。链接

【SQLite is a lightweight, serverless, self-contained SQL database engine that is widely used for local data storage in applications. Read more here.

示例用法

【Example Usage】

Better Auth 支持多种 SQLite 驱动。请选择最适合你环境的驱动:

【Better Auth supports multiple SQLite drivers. Choose the one that best fits your environment:】

【Better-SQLite3 (Recommended)】

Node.js 最流行且稳定的 SQLite 驱动:

【The most popular and stable SQLite driver for Node.js:】

auth.ts
import { betterAuth } from "better-auth";
import Database from "better-sqlite3";

export const auth = betterAuth({
  database: new Database("database.sqlite"),
});

欲了解更多信息,请阅读 Kysely 关于 SqliteDialect 的文档。

Node.js 内置 SQLite(实验性)

【Node.js Built-in SQLite (Experimental)】

node:sqlite 模块仍处于实验阶段,可能随时发生更改。它需要 Node.js 22.5.0 或更高版本。

从 Node.js 22.5.0 开始,你可以使用内置的 SQLite 模块:

【Starting from Node.js 22.5.0, you can use the built-in SQLite module:】

auth.ts
import { betterAuth } from "better-auth";
import { DatabaseSync } from "node:sqlite";

export const auth = betterAuth({
  database: new DatabaseSync("database.sqlite"),
});

使用 Node.js SQLite 运行你的应用:

【To run your application with Node.js SQLite:】

node your-app.js

Bun 内置 SQLite

【Bun Built-in SQLite】

你也可以使用 Bun 内置的 SQLite 模块,它与 Node.js 版本类似:

【You can also use the built-in SQLite module in Bun, which is similar to the Node.js version:】

auth.ts
import { betterAuth } from "better-auth";
import { Database } from "bun:sqlite";
export const auth = betterAuth({
  database: new Database("database.sqlite"),
});

架构生成与迁移

【Schema generation & migration】

Better Auth CLI 允许你根据你的 Better Auth 配置和插件生成或迁移数据库模式。

【The Better Auth CLI allows you to generate or migrate your database schema based on your Better Auth configuration and plugins.】

SQLite 模式生成

SQLite 模式迁移

✅ 支持✅ 支持
Schema Generation
npx @better-auth/cli@latest generate
Schema Migration
npx @better-auth/cli@latest migrate

联接(实验性)

【Joins (Experimental)】

当 Better-Auth 需要在单个查询中从多张表获取相关数据时,数据库连接(joins)非常有用。像 /get-session/get-full-organization 等端点以及许多其他端点都极大地受益于这一功能,根据数据库延迟的不同,性能提升可达 2 到 3 倍。

【Database joins is useful when Better-Auth needs to fetch related data from multiple tables in a single query. Endpoints like /get-session, /get-full-organization and many others benefit greatly from this feature, seeing upwards of 2x to 3x performance improvements depending on database latency.】

1.4.0 版本起,Kysely SQLite 方言原生支持连接(joins)。 要启用此功能,你需要在认证配置中将 experimental.joins 选项设置为 true

【The Kysely SQLite dialect supports joins out of the box since version 1.4.0. To enable this feature, you need to set the experimental.joins option to true in your auth configuration.】

auth.ts
export const auth = betterAuth({
  experimental: { joins: true }
});

It's possible that you may need to run migrations after enabling this feature.

附加信息

【Additional Information】

SQLite 在底层通过 Kysely 适配器提供支持,Kysely 支持的任何数据库也将被支持。(在此处了解更多)

如果你正在寻找性能改进或技巧,请查看我们的 性能优化指南

On this page