Better Auth para Next.js App Router: route handler, redirecionamentos no proxy e sessão no servidor
Código5 arquivosContexto~545 tokensanálise aprovada
Instalar
$
genpm add @yohangel/auth-nextO que você recebe
- Código em src/lib/auth-next/, 5 arquivos. (6,4 kB)
- Regras de IA em src/lib/auth-next/AGENTS.md, mais arquivos de regras da IDE.
- Resolve @yohangel/auth para você.
README
Este pacote não tem README.
~545 tokens→ src/lib/auth-next/AGENTS.md→ .cursor/rules/genpm-yohangel-auth-next.mdc
Isto é exatamente o que sua IA lê quando trabalha em src/lib/auth-next. Nada mais é adicionado ao contexto dela.
@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.
A árvore exata que será injetada, após o .genpmignore. Fixada em
// Servidor (App Router): instancia de la app con `nextCookies()` (para que las Server Actions puedan fijar cookies),
// handler de las rutas /api/auth/* y helpers de sesión para Server Components, Route Handlers y Server Actions.
import { nextCookies, toNextJsHandler } from 'better-auth/next-js';
import { headers } from 'next/headers.js';
import { redirect } from 'next/navigation.js';
import { type AuthSession, type CreateAuthOptions, createAuth } from '../auth/index.js';
/** Plugins extra van antes de `nextCookies()`, que debe ser el último. */
export function createNextAuth(opts: CreateAuthOptions = {}) {
return createAuth({ ...opts, plugins: [...(opts.plugins ?? []), nextCookies()] });
}
export const auth = createNextAuth();
/** app/api/auth/[...all]/route.ts → `export const { GET, POST } = authRouteHandlers;` */
export const authRouteHandlers = toNextJsHandler(auth);
/** Sesión de la petición actual (null si no hay). Comprobación real contra la BD (o su caché firmada). */
export async function currentSession(): Promise<AuthSession | null> {
return auth.api.getSession({ headers: await headers() });
}
/** Exige sesión: si no la hay, redirige a `signInPath` con `?next=` para volver después. */
export async function requireSession(signInPath = '/sign-in', next?: string): Promise<AuthSession> {
const s = await currentSession();
if (!s) redirect(next ? `${signInPath}?next=${encodeURIComponent(next)}` : signInPath);
return s;
}
Este pacote não declara servidores MCP.
| Versão | Commit | Publicado | Análise |
|---|---|---|---|
| 1.0.0 | 7145b9d | há 3 horas | ✔ análise aprovada |
- npm
- nenhum
- proposto
- O GenPM propõe o comando npm e só o executa se você disser sim.
- análise
- análise aprovada · 0 achados
- commit
- auth-next@1.0.0 → 7145b9d58055b5145085782c958b7577f1d65276 · verificado após o download
- scripts
- Nenhum. O GenPM nunca executa código de pacotes.
- licença
- MIT
- denúncia
- Viu algo errado?