Better Auth for Next.js App Router: route handler, proxy redirects and server session helpers
Code5 filesContext~545 tokensscan passed
Install
$
genpm add @yohangel/auth-nextWhat you get
- Source in src/lib/auth-next/, 5 files. (6.4 kB)
- AI rules in src/lib/auth-next/AGENTS.md, plus IDE rule files.
- Resolves @yohangel/auth for you.
README
This package has no README.
~545 tokens→ src/lib/auth-next/AGENTS.md→ .cursor/rules/genpm-yohangel-auth-next.mdc
This is exactly what your AI reads when it works in src/lib/auth-next. Nothing else is added to its context.
@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.
The exact tree that will be injected, after .genpmignore. Pinned to
// 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;
}
This package declares no MCP servers.
| Version | Commit | Published | Scan |
|---|---|---|---|
| 1.0.0 | 7145b9d | 2 hours ago | ✔ scan passed |
- npm
- none
- proposed
- GenPM proposes the npm command and runs it only if you say yes.
- scan
- scan passed · 0 findings
- commit
- auth-next@1.0.0 → 7145b9d58055b5145085782c958b7577f1d65276 · verified after fetch
- scripts
- None. GenPM never runs package code.
- license
- MIT
- report
- See something wrong?