Cursor rule for Next.js auth with optimistic Proxy checks, a server-only Data Access Layer, checks inside every Server Action and Route Handler, and safe cookies.
.cursor/rules/next-js-authentication-patterns.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for Next.js auth with optimistic Proxy checks, a server-only Data Access Layer, checks inside every Server Action and Route Handler, and safe cookies."
globs: "**/*"
alwaysApply: false
---
# Next.js Authentication Patterns
Applies to: sign-in, session handling and authorization checks in a Next.js App Router project.
Version baseline: checked against the Next.js 16.3 authentication, data security and Server Actions guides. Read `package.json` first. In Next.js 16 the request interceptor file is `proxy.ts` (`middleware.ts` is deprecated); on Next.js 15 and earlier keep `middleware.ts`. If the project uses an auth library, follow that library's current documentation for session creation instead of hand-rolling crypto.
## Where each check belongs
1. **Proxy (optional, optimistic only).** `proxy.ts` may redirect users without a session cookie away from protected pages. It runs on every matched route, including prefetches, so read the cookie only; never query the database there and never treat it as the only protection.
2. **Data Access Layer (required).** Put `verifySession()` and authorization rules in one server-only module and call it from every function that reads or writes protected data.
3. **Server Actions and Route Handlers (required).** Each one is a reachable POST/HTTP endpoint. Authenticate and authorize inside it, even if the form is only rendered for signed-in users.
```ts
// lib/dal.ts
import 'server-only'
import { cache } from 'react'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { decryptSession } from '@/lib/session'
export const verifySession = cache(async () => {
const token = (await cookies()).get('session')?.value
const session = token ? await decryptSession(token) : null
if (!session) redirect('/login')
return { userId: session.userId, role: session.role }
})
```
```ts
// app/admin/actions.ts
'use server'
import { revalidatePath } from 'next/cache'
import { verifySession } from '@/lib/dal'
import { db } from '@/lib/db'
export async function deletePost(postId: string) {
const session = await verifySession()
if (session.role !== 'ADMIN') throw new Error('Forbidden')
await db.post.delete({ where: { id: postId } })
revalidatePath('/admin/posts')
}
```
```ts
// proxy.ts
import { NextResponse, type NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const hasSession = request.cookies.has('session')
if (!hasSession && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url))
}
return NextResponse.next()
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
}
```
## Sessions and cookies
- `cookies()` is async: `const store = await cookies()`. Set cookies only in Server Actions or Route Handlers.
- Session cookies: `httpOnly: true`, `secure: true` in production, `sameSite: 'lax'` (or `'strict'` if cross-site entry links are not needed), `path: '/'` and an explicit `expires`/`maxAge`.
- Store an opaque session ID (database sessions) or a signed and encrypted payload (stateless sessions). Never put tokens in `localStorage` or in props passed to Client Components.
- Rotate or re-issue the session after sign-in, privilege changes and password resets; delete it on sign-out on both the server store and the cookie.
- If the app uses refresh tokens from an external identity provider, refresh them server-side and keep them in httpOnly cookies or the server session.
## Requests that change state
- Server Actions are POST-only and Next.js compares the `Origin` header with `Host` (or `X-Forwarded-Host`). Behind a reverse proxy with a different host, configure `serverActions.allowedOrigins` instead of disabling checks.
- Custom Route Handlers that change state get no such check: require a non-GET method, verify the session, and validate `Origin` or a CSRF token when they accept cookie-authenticated browser requests.
- Validate every input with a schema; return the same generic message for "unknown user" and "wrong password".
## Rate limiting
Rate-limit sign-in, sign-up, password reset and OTP endpoints per account and per client IP, using a shared store the project already runs (Redis, database table, or the hosting provider's limiter). Return HTTP 429 with `Retry-After`. An in-memory counter is not sufficient when the app runs on more than one instance.
## Data exposure
- Return DTOs from the Data Access Layer: only the fields the UI needs. Do not pass full user records to Client Components.
- Do not rely on layouts for auth checks: layouts do not re-render on navigation. Check in the page, the action or the data function.
## Verify before finishing
- `npx tsc --noEmit` passes (catches un-awaited `cookies()`).
- For each new Server Action or Route Handler, a test or manual `curl` without a session cookie gets 401/403 or a redirect, never data.
- Session cookie flags verified in browser dev tools (HttpOnly, Secure, SameSite).
- `grep -rn "localStorage" app lib` finds no auth token storage.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
security
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Protecting an admin area and its delete action in a Next.js 16 app that stores an encrypted session ID in a cookie.
Only ADMIN users may open /admin/posts and call the deletePost action. We use a session cookie named 'session' decrypted by decryptSession() in lib/session.ts. Add the protection.
Illustrative; not a recorded model run. A lib/dal.ts with import 'server-only', a React cache()-wrapped verifySession that awaits cookies() and redirects when missing; deletePost re-checking session and role inside the action before writing and revalidating; an optional proxy.ts that only checks cookie presence; cookie flags httpOnly, secure, sameSite and expiry; a note that rendering the button only for admins is not protection; rate limiting on login with 429 + Retry-After using the project's shared store.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/next-js-authentication-patterns.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Next.js Authentication Patterns: Proxy, Data Access Layer and Protected Actions project conventions"
globs: "**/*"
alwaysApply: false
---
# Next.js Authentication Patterns
Applies to: sign-in, session handling and authorization checks in a Next.js App Router project.
Version baseline: checked against the Next.js 16.3 authentication, data security and Server Actions guides. Read `package.json` first. In Next.js 16 the request interceptor file is `proxy.ts` (`middleware.ts` is deprecated); on Next.js 15 and earlier keep `middleware.ts`. If the project uses an auth library, follow that library's current documentation for session creation instead of hand-rolling crypto.
## Where each check belongs
1. **Proxy (optional, optimistic only).** `proxy.ts` may redirect users without a session cookie away from protected pages. It runs on every matched route, including prefetches, so read the cookie only; never query the database there and never treat it as the only protection.
2. **Data Access Layer (required).** Put `verifySession()` and authorization rules in one server-only module and call it from every function that reads or writes protected data.
3. **Server Actions and Route Handlers (required).** Each one is a reachable POST/HTTP endpoint. Authenticate and authorize inside it, even if the form is only rendered for signed-in users.
```ts
// lib/dal.ts
import 'server-only'
import { cache } from 'react'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { decryptSession } from '@/lib/session'
export const verifySession = cache(async () => {
const token = (await cookies()).get('session')?.value
const session = token ? await decryptSession(token) : null
if (!session) redirect('/login')
return { userId: session.userId, role: session.role }
})
```
```ts
// app/admin/actions.ts
'use server'
import { revalidatePath } from 'next/cache'
import { verifySession } from '@/lib/dal'
import { db } from '@/lib/db'
export async function deletePost(postId: string) {
const session = await verifySession()
if (session.role !== 'ADMIN') throw new Error('Forbidden')
await db.post.delete({ where: { id: postId } })
revalidatePath('/admin/posts')
}
```
```ts
// proxy.ts
import { NextResponse, type NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const hasSession = request.cookies.has('session')
if (!hasSession && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url))
}
return NextResponse.next()
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
}
```
## Sessions and cookies
- `cookies()` is async: `const store = await cookies()`. Set cookies only in Server Actions or Route Handlers.
- Session cookies: `httpOnly: true`, `secure: true` in production, `sameSite: 'lax'` (or `'strict'` if cross-site entry links are not needed), `path: '/'` and an explicit `expires`/`maxAge`.
- Store an opaque session ID (database sessions) or a signed and encrypted payload (stateless sessions). Never put tokens in `localStorage` or in props passed to Client Components.
- Rotate or re-issue the session after sign-in, privilege changes and password resets; delete it on sign-out on both the server store and the cookie.
- If the app uses refresh tokens from an external identity provider, refresh them server-side and keep them in httpOnly cookies or the server session.
## Requests that change state
- Server Actions are POST-only and Next.js compares the `Origin` header with `Host` (or `X-Forwarded-Host`). Behind a reverse proxy with a different host, configure `serverActions.allowedOrigins` instead of disabling checks.
- Custom Route Handlers that change state get no such check: require a non-GET method, verify the session, and validate `Origin` or a CSRF token when they accept cookie-authenticated browser requests.
- Validate every input with a schema; return the same generic message for "unknown user" and "wrong password".
## Rate limiting
Rate-limit sign-in, sign-up, password reset and OTP endpoints per account and per client IP, using a shared store the project already runs (Redis, database table, or the hosting provider's limiter). Return HTTP 429 with `Retry-After`. An in-memory counter is not sufficient when the app runs on more than one instance.
## Data exposure
- Return DTOs from the Data Access Layer: only the fields the UI needs. Do not pass full user records to Client Components.
- Do not rely on layouts for auth checks: layouts do not re-render on navigation. Check in the page, the action or the data function.
## Verify before finishing
- `npx tsc --noEmit` passes (catches un-awaited `cookies()`).
- For each new Server Action or Route Handler, a test or manual `curl` without a session cookie gets 401/403 or a redirect, never data.
- Session cookie flags verified in browser dev tools (HttpOnly, Secure, SameSite).
- `grep -rn "localStorage" app lib` finds no auth token storage.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.