Next.js App Router 用 Better Auth:ルートハンドラー、proxy リダイレクト、サーバー側セッション
コード5 ファイルコンテキスト約 545 トークンスキャン合格
インストール
$
genpm add @yohangel/auth-next含まれるもの
- src/lib/auth-next/ にソースコード(5 ファイル)。 (6.4 KB)
- src/lib/auth-next/AGENTS.md に AI ルール、加えて IDE 用のルールファイル。
- @yohangel/auth を自動で解決します。
README
このパッケージには README がありません。
約 545 トークン→ 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
- 報告
- 問題を見つけましたか?