PostgreSQL 适配器
资源
设置
安装
npm install @auth/pg-adapter pg
环境变量
DATABASE_HOST=
DATABASE_NAME=
DATABASE_USER=
DATABASE_PASSWORD=
配置
./auth.ts
import NextAuth from "next-auth"
import PostgresAdapter from "@auth/pg-adapter"
import { Pool } from "pg"
const pool = new Pool({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
})
export const { handlers, auth, signIn, signOut } = NextAuth({
adapter: PostgresAdapter(pool),
providers: [],
})
如果您使用的是像 Neon 的 Vercel Postgres 这样的 PostgreSQL,您可以使用 @neondatabase/serverless
来处理边缘运行时。
./auth.ts
import NextAuth from "next-auth"
import PostgresAdapter from "@auth/pg-adapter"
import { Pool } from "@neondatabase/serverless"
// *DO NOT* create a `Pool` here, outside the request handler.
// Neon's Postgres cannot keep a pool alive between requests.
export const { handlers, auth, signIn, signOut } = NextAuth(() => {
// Create a `Pool` inside the request handler.
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
return {
adapter: PostgresAdapter(pool),
providers: [],
}
})
架构
此适配器使用的表的 SQL 架构如下。详细了解我们的文档页面上关于 数据库模型 的模型。
CREATE TABLE verification_token
(
identifier TEXT NOT NULL,
expires TIMESTAMPTZ NOT NULL,
token TEXT NOT NULL,
PRIMARY KEY (identifier, token)
);
CREATE TABLE accounts
(
id SERIAL,
"userId" INTEGER NOT NULL,
type VARCHAR(255) NOT NULL,
provider VARCHAR(255) NOT NULL,
"providerAccountId" VARCHAR(255) NOT NULL,
refresh_token TEXT,
access_token TEXT,
expires_at BIGINT,
id_token TEXT,
scope TEXT,
session_state TEXT,
token_type TEXT,
PRIMARY KEY (id)
);
CREATE TABLE sessions
(
id SERIAL,
"userId" INTEGER NOT NULL,
expires TIMESTAMPTZ NOT NULL,
"sessionToken" VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE users
(
id SERIAL,
name VARCHAR(255),
email VARCHAR(255),
"emailVerified" TIMESTAMPTZ,
image TEXT,
PRIMARY KEY (id)
);