# Neon Auth - 认证方法参考
关于认证方法、会话管理和错误处理的完整参考。
## 认证方法
### 注册 (Sign Up)
typescript
await auth.signUp.email({
email: "
[email protected]",
password: "securepassword",
name: "John Doe", // 可选
});
### 登录 (Sign In)
typescript
// 邮箱/密码
await auth.signIn.email({
email: "
[email protected]",
password: "securepassword",
});
// 社交登录 (Google, GitHub)
await auth.signIn.social({
provider: "google", // 或 "github"
callbackURL: "/dashboard",
});
### 登出 (Sign Out)
typescript
await auth.signOut();
### 获取会话 (Get Session)
typescript
// 异步 (Node.js, 服务端组件)
const session = await auth.getSession();
// React Hook (客户端组件)
const session = auth.useSession();
// 返回: { data: Session | null, isPending: boolean }
## 会话数据结构
typescript
interface Session {
user: {
id: string;
name: string | null;
email: string;
image: string | null;
emailVerified: boolean;
createdAt: Date;
updatedAt: Date;
};
session: {
id: string;
expiresAt: Date;
token: string;
createdAt: Date;
updatedAt: Date;
userId: string;
};
}
## 错误处理
typescript
const { error } = await auth.signIn.email({ email, password });
if (error) {
switch (error.code) {
case "INVALID_EMAIL_OR_PASSWORD":
showError("邮箱或密码无效");
break;
case "EMAIL_NOT_VERIFIED":
showError("请验证您的邮箱");
break;
case "USER_NOT_FOUND":
showError("未找到用户");
break;
case "TOO_MANY_REQUESTS":
showError("尝试次数过多,请稍后再试。");
break;
default:
showError("认证失败");
}
}
## 构建认证页面
### 使用 AuthView (推荐用于 React 应用)
对于认证页面,请使用预构建的 `AuthView` 组件,而不是手动构建表单。
**AuthView 提供的内容:**
- 登录、注册、密码重置、魔法链接页面
- 社交提供商 (Google, GitHub) - 需要两步配置:在 Neon 控制台启用并在 NeonAuthUIProvider 中添加 `social` 属性
- 表单验证、错误处理、加载状态
- 通过 CSS 变量实现的一致性样式
**设置 (Next.js App Router):**
1. **导入 CSS** (在 `app/layout.tsx` 或 `app/globals.css` 中):
tsx
import "@neondatabase/auth/ui/css";
2. **使用 Provider 包裹应用** (创建 `app/auth-provider.tsx`):
tsx
"use client";
impo