跳至内容
从 NextAuth.js v4 迁移?阅读 我们的迁移指南.

SurrealDB 适配器

资源

设置

安装

npm install @auth/surrealdb-adapter surrealdb.js

环境变量

AUTH_SURREALDB_CONNECTION
AUTH_SURREALDB_USERNAME
AUTH_SURREALDB_PASSWORD
AUTH_SURREALDB_NS
AUTH_SURREALDB_DB

配置

./auth.ts
import NextAuth from "next-auth"
import { SurrealDBAdapter } from "@auth/surrealdb-adapter"
import clientPromise from "./lib/surrealdb"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [],
  adapter: SurrealDBAdapter(clientPromise),
})

SurrealDB 适配器不会自动处理连接,因此您需要确保将已连接的 SurrealDBClient 传递给适配器。下面您可以看到一个示例,说明如何执行此操作。

授权

选项 1 – 使用 RPC:

./lib/surrealdb.ts
import { Surreal } from "surrealdb.js"
 
const connectionString = process.env.AUTH_SURREALDB_CONNECTION
const username = process.env.AUTH_SURREALDB_USERNAME
const password = process.env.AUTH_SURREALDB_PASSWORD
const namespace = process.env.AUTH_SURREALDB_NAMESPACE
const database = process.env.AUTH_SURREALDB_DATABASE
if (!connectionString || !username || !password || !namespace || !database) {
  throw new Error(
    "SurrealDB connection string, username, password, namespace, and database are required"
  )
}
 
const clientPromise = new Promise<Surreal>(async (resolve, reject) => {
  const db = new Surreal()
  try {
    await db.connect(`${connectionString}/rpc`, {
      namespace,
      database,
      auth: {
        username,
        password,
      },
    })
    resolve(db)
  } catch (e) {
    reject(e)
  }
})
 
// Export a module-scoped Promise<Surreal>. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise

选项 2 – 使用 HTTP:

在 Vercel 等无服务器环境中很有用。

./lib/surrealdb.ts
import { ExperimentalSurrealHTTP } from "surrealdb.js"
 
const connectionString = process.env.AUTH_SURREALDB_CONNECTION
const username = process.env.AUTH_SURREALDB_USERNAME
const password = process.env.AUTH_SURREALDB_PASSWORD
const namespace = process.env.AUTH_SURREALDB_NAMESPACE
const database = process.env.AUTH_SURREALDB_DATABASE
if (!connectionString || !username || !password || !namespace || !database) {
  throw new Error(
    "SurrealDB connection string, username, password, namespace, and database are required"
  )
}
 
const clientPromise = new Promise<ExperimentalSurrealHTTP<typeof fetch>>(
  async (resolve, reject) => {
    try {
      const db = new ExperimentalSurrealHTTP(connectionString, {
        fetch,
        namespace,
        database,
        auth: {
          username,
          password,
        },
      })
      resolve(db)
    } catch (e) {
      reject(e)
    }
  }
)
 
// Export a module-scoped Promise<Surreal>. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise
Auth.js © Balázs Orbán 和团队 -2024