适用于 Next.js App Router 的 Better Auth:路由处理器、proxy 重定向和服务端会话
代码5 个文件上下文约 545 个 token扫描通过
安装
$
genpm add @yohangel/auth-next你将获得
- 源代码位于 src/lib/auth-next/,共 5 个文件。 (6.4 kB)
- AI 规则位于 src/lib/auth-next/AGENTS.md,另附 IDE 规则文件。
- 自动为你解析 @yohangel/auth。
README
此包没有 README。
约 545 个 token→ src/lib/auth-next/AGENTS.md→ .cursor/rules/genpm-yohangel-auth-next.mdc
这正是你的 AI 在 src/lib/auth-next 中工作时读取的内容。不会向其上下文添加其他任何内容。
@yohangel/auth-next — rules for AI agents
Purpose
Connects @yohangel/auth to the Next.js App Router (Next 15/16): the /api/auth/* route handler, optimistic redirects in proxy.ts, and server-side session helpers. For forms and useSession, also install @yohangel/auth-react.
Module map
index.ts— public API.server.ts—auth(instance withnextCookies()),authRouteHandlers,currentSession(),requireSession(signInPath, next),createNextAuth(opts).proxy.ts—authProxy({ protect, signInPath })andsafeNext(next).
Integration (do this after installing)
- Route handler — create
app/api/auth/[...all]/route.ts(orsrc/app/...):import { authRouteHandlers } from '@/lib/auth-next'; export const { GET, POST } = authRouteHandlers; - Edge redirects — create
proxy.tsat the project root (Next 16; on Next 15 name itmiddleware.tsand exportmiddleware):import { authProxy } from '@/lib/auth-next'; export const proxy = authProxy({ protect: ['/dashboard', '/settings'], signInPath: '/sign-in' }); export const config = { matcher: ['/dashboard/:path*', '/settings/:path*'] }; - In every private page, layout, Route Handler and Server Action, check for real:
const { user } = await requireSession('/sign-in', '/dashboard');. - Sign-in page: render
SignInFormfrom@yohangel/auth-reactwithredirectTo={safeNext(searchParams.next)}. - Need emails or extra plugins? Edit
server.ts:export const auth = createNextAuth({ sendEmail, plugins: [...] })—nextCookies()is appended last automatically.
Conventions
- Import the instance from this package (
auth), never callcreateAuthagain elsewhere in a Next app. - Server Components read the session with
currentSession(); pass only the fields the client needs (never the session token).
Don't
- Don't treat
proxy.tsas authorization: it only checks that a cookie exists. Always callrequireSession()/currentSession()on the server. - Don't redirect to
?next=values withoutsafeNext()(open redirect). - Don't expose
auth.apicalls in Client Components; they run on the server only.
# @yohangel/auth-next — rules for AI agents
## Purpose
Connects `@yohangel/auth` to the Next.js App Router (Next 15/16): the `/api/auth/*` route handler, optimistic redirects in `proxy.ts`, and server-side session helpers. For forms and `useSession`, also install `@yohangel/auth-react`.
## Module map
- `index.ts` — public API.
- `server.ts` — `auth` (instance with `nextCookies()`), `authRouteHandlers`, `currentSession()`, `requireSession(signInPath, next)`, `createNextAuth(opts)`.
- `proxy.ts` — `authProxy({ protect, signInPath })` and `safeNext(next)`.
## Integration (do this after installing)
1. Route handler — create `app/api/auth/[...all]/route.ts` (or `src/app/...`):
```ts
import { authRouteHandlers } from '@/lib/auth-next';
export const { GET, POST } = authRouteHandlers;
```
2. Edge redirects — create `proxy.ts` at the project root (Next 16; on Next 15 name it `middleware.ts` and export `middleware`):
```ts
import { authProxy } from '@/lib/auth-next';
export const proxy = authProxy({ protect: ['/dashboard', '/settings'], signInPath: '/sign-in' });
export const config = { matcher: ['/dashboard/:path*', '/settings/:path*'] };
```
3. In every private page, layout, Route Handler and Server Action, check for real: `const { user } = await requireSession('/sign-in', '/dashboard');`.
4. Sign-in page: render `SignInForm` from `@yohangel/auth-react` with `redirectTo={safeNext(searchParams.next)}`.
5. Need emails or extra plugins? Edit `server.ts`: `export const auth = createNextAuth({ sendEmail, plugins: [...] })` — `nextCookies()` is appended last automatically.
## Conventions
- Import the instance from this package (`auth`), never call `createAuth` again elsewhere in a Next app.
- Server Components read the session with `currentSession()`; pass only the fields the client needs (never the session token).
## Don't
- Don't treat `proxy.ts` as authorization: it only checks that a cookie exists. Always call `requireSession()` / `currentSession()` on the server.
- Don't redirect to `?next=` values without `safeNext()` (open redirect).
- Don't expose `auth.api` calls in Client Components; they run on the server only.
应用 .genpmignore 后将被注入的确切目录树。固定于
// Protección optimista en el borde (Next 16 `proxy.ts`, o `middleware.ts` en Next 15): solo mira si existe la
// cookie de sesión, sin tocar la BD. NO es una comprobación de seguridad: valida siempre con `requireSession()` en
// la página o acción. Sirve para redirigir rápido a quien claramente no ha iniciado sesión.
import { getSessionCookie } from 'better-auth/cookies';
import { type NextRequest, NextResponse } from 'next/server.js';
export type AuthProxyOptions = {
/** Prefijos de ruta privados, p. ej. ['/dashboard', '/settings']. */
protect: string[];
/** Página de inicio de sesión. */
signInPath?: string;
};
export function authProxy({ protect, signInPath = '/sign-in' }: AuthProxyOptions) {
return (request: NextRequest) => {
const { pathname, search } = request.nextUrl;
const isPrivate = protect.some((p) => pathname === p || pathname.startsWith(`${p}/`));
if (!isPrivate || getSessionCookie(request)) return NextResponse.next();
const url = new URL(signInPath, request.url);
url.searchParams.set('next', `${pathname}${search}`);
return NextResponse.redirect(url);
};
}
/** Solo rutas internas: evita redirecciones abiertas con `?next=https://evil.example`. */
export function safeNext(next: string | null | undefined, fallback = '/'): string {
return next?.startsWith('/') && !next.startsWith('//') && !next.startsWith('/\\') ? next : fallback;
}
此包未声明 MCP 服务器。
| 版本 | 提交 | 发布时间 | 扫描 |
|---|---|---|---|
| 1.0.0 | 7145b9d | 3小时前 | ✔ 扫描通过 |
- npm
- 无
- 建议
- GenPM 会给出 npm 命令建议,只有你同意时才会运行。
- 扫描
- 扫描通过 · 0 个问题
- 提交
- auth-next@1.0.0 → 7145b9d58055b5145085782c958b7577f1d65276 · 获取后已校验
- 脚本
- 无。GenPM 从不运行包中的代码。
- 许可证
- MIT
- 举报
- 发现问题了吗?