Claude Code से सुरक्षित Cookie Management: Next.js Session, CSRF और Consent Boundary
Claude Code से सुरक्षित Next.js cookies बनाएं: HttpOnly, Secure, SameSite, CSRF, logout और consent boundary।
Cookie management छोटा काम लगता है, लेकिन authentication में यही सबसे संवेदनशील जगहों में से एक है। Browser हर request के साथ Cookie अपने आप भेज सकता है। यही सुविधा login के लिए उपयोगी है, और यही बात गलत attributes होने पर account takeover, CSRF या logout bug का कारण बन सकती है।
Claude Code जल्दी code बना देता है, पर अगर prompt केवल “login cookie set कर दो” है, तो जरूरी बातें छूट सकती हैं। HttpOnly नहीं लगेगा, SameSite=None के साथ Secure नहीं होगा, logout में Path mismatch होगा, या analytics cookie और authentication cookie एक ही consent logic में मिल जाएंगे।
इस article में Next.js App Router के लिए सुरक्षित Cookie workflow है: inventory, copy-pasteable Route Handler, logout, server-side read, CSRF token, session fixation से बचाव, browser behavior, consent boundary, verification commands और official references। HttpOnly का मतलब है “JavaScript से Cookie पढ़ने से रोकना”; SameSite का मतलब है “cross-site request में browser Cookie भेजे या नहीं”।
पहले Cookie inventory बनाएं
Attributes चुनने से पहले Cookie का purpose लिखें। Authentication Cookie credential है। Preference Cookie theme या language जैसी setting है। Analytics और ads Cookie tracking के लिए हैं। इन तीनों को एक ही consent और security rule से नहीं संभालना चाहिए।
| Purpose | Example | Recommended attributes | Consent boundary |
|---|---|---|---|
| Authentication session | __Host-session | HttpOnly, Secure, SameSite=Lax, Path=/, छोटा Max-Age | अक्सर requested service के लिए necessary, पर local rules check करें |
| CSRF token | csrf-token | Secure, SameSite=Lax, छोटा Max-Age | Security helper, analytics ID नहीं |
| UI preference | theme, locale | Secure, SameSite=Lax, limited lifetime | region और policy के अनुसार explain करें |
| Analytics या ads | _ga, campaign ID | consent required हो तो consent के बाद ही set करें | login और checkout से अलग |
MDN की Secure cookie configuration guide Secure, HttpOnly, SameSite और prefixes से scope कम करने की सलाह देती है। MDN Set-Cookie reference बताता है कि SameSite=None के साथ Secure जरूरी है, और Max-Age तथा Expires दोनों हों तो Max-Age priority लेता है।
Session Cookie के लिए __Host- prefix बेहतर है। Supporting browsers में यह तभी valid है जब Secure हो, Domain न हो, और Path=/ हो। इससे subdomain द्वारा session Cookie overwrite करने का risk घटता है।
Next.js में secure session cookie set करें
Next.js की cookies API cookies() को async API के रूप में document करती है और httpOnly, secure, sameSite, maxAge, path, domain जैसे options देती है। Server Components Cookie पढ़ सकते हैं; set और delete Route Handler या Server Action में करें।
यह code app/api/login/route.ts में रखा जा सकता है। Demo के लिए memory Map है। Production में Redis, PostgreSQL, DynamoDB या किसी persistent session store का उपयोग करें।
import { createHmac, randomBytes } from "node:crypto";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
export const runtime = "nodejs";
const env = z
.object({
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
SESSION_SECRET: z.string().min(32),
})
.parse(process.env);
const SESSION_COOKIE = "__Host-session";
const SESSION_MAX_AGE_SECONDS = 60 * 60 * 8;
type SessionRecord = {
userId: string;
expiresAt: number;
};
declare global {
var demoSessions: Map<string, SessionRecord> | undefined;
}
const sessions = globalThis.demoSessions ?? new Map<string, SessionRecord>();
globalThis.demoSessions = sessions;
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(12),
});
function createSessionToken() {
const id = randomBytes(32).toString("base64url");
const signature = createHmac("sha256", env.SESSION_SECRET)
.update(id)
.digest("base64url");
return `${id}.${signature}`;
}
async function authenticate(email: string, password: string) {
if (email === "masa@example.com" && password === "correct-horse-battery-staple") {
return { id: "user_123" };
}
return null;
}
export async function POST(request: NextRequest) {
const body = loginSchema.safeParse(await request.json());
if (!body.success) {
return NextResponse.json({ error: "Invalid login payload" }, { status: 400 });
}
const user = await authenticate(body.data.email, body.data.password);
if (!user) {
return NextResponse.json({ error: "Invalid credentials" }, { status: 401 });
}
const token = createSessionToken();
sessions.set(token, {
userId: user.id,
expiresAt: Date.now() + SESSION_MAX_AGE_SECONDS * 1000,
});
const response = NextResponse.json({ ok: true });
response.cookies.set({
name: SESSION_COOKIE,
value: token,
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
maxAge: SESSION_MAX_AGE_SECONDS,
});
return response;
}
हर successful login पर नया token बनता है। यह session fixation से बचाता है। Session fixation में attacker पहले से known session ID देता है और user उसी ID से login कर लेता है। OWASP का Session Fixation page इस attack को समझाता है।
Logout और server-side read
Cookie delete करते समय केवल name काफी नहीं है। Scope भी match होना चाहिए। अगर Cookie Path=/ के साथ set हुई है, तो delete भी Path=/ से करें। अगर Domain set किया था, delete में भी वही Domain चाहिए। __Host- Cookie में Domain नहीं होना चाहिए।
app/api/logout/route.ts:
import { NextResponse } from "next/server";
const SESSION_COOKIE = "__Host-session";
export async function POST() {
const response = NextResponse.json({ ok: true });
response.cookies.set({
name: SESSION_COOKIE,
value: "",
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
maxAge: 0,
});
return response;
}
Production में server-side session store से भी session revoke करें। Browser Cookie हटाने से stolen token हमेशा तुरंत invalid नहीं होता।
Server Component में read:
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
const SESSION_COOKIE = "__Host-session";
export default async function AccountPage() {
const cookieStore = await cookies();
const sessionToken = cookieStore.get(SESSION_COOKIE)?.value;
if (!sessionToken) {
redirect("/login");
}
return <main>Account dashboard</main>;
}
Cookie मौजूद है, इसका मतलब user authenticated है, ऐसा न मानें। Server को session store, expiry, revoke status, user और permissions check करने चाहिए।
CSRF केवल HttpOnly से नहीं रुकता
CSRF यानी cross-site request forgery: कोई दूसरा site logged-in browser से unwanted request भेजवा देता है। Browser Cookie अपने आप भेजता है, इसलिए HttpOnly Cookie को JavaScript से पढ़ने से रोकता है, पर request भेजने से नहीं रोकता।
OWASP CSRF Prevention Cheat Sheet state-changing requests के लिए CSRF token की सलाह देता है। यह helper session token से जुड़ा signed token बनाता है।
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
const CSRF_SECRET = process.env.SESSION_SECRET;
if (!CSRF_SECRET || CSRF_SECRET.length < 32) {
throw new Error("SESSION_SECRET must be at least 32 characters");
}
export function createCsrfToken(sessionToken: string) {
const nonce = randomBytes(16).toString("base64url");
const signature = createHmac("sha256", CSRF_SECRET)
.update(`${sessionToken}.${nonce}`)
.digest("base64url");
return `${nonce}.${signature}`;
}
export function verifyCsrfToken(sessionToken: string, token: string) {
const [nonce, signature] = token.split(".");
if (!nonce || !signature) return false;
const expected = createHmac("sha256", CSRF_SECRET)
.update(`${sessionToken}.${nonce}`)
.digest("base64url");
return timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}
POST, PUT, PATCH और DELETE में token require करें। GET से state change न करें। SameSite=Lax helpful है, लेकिन token, Origin check और सही HTTP method का substitute नहीं है। XSS होने पर CSRF defenses bypass हो सकते हैं, इसलिए output escaping और CSP भी जरूरी हैं।
Browser behavior और expiry
Browser frontend JavaScript को Set-Cookie header expose नहीं करता। DevTools या curl -i में header दिखेगा, लेकिन fetch() response headers से पढ़ना reliable नहीं है। Cross-origin requests में CORS और credentials भी सही चाहिए।
Max-Age relative seconds है। Expires fixed date है। Application code में Max-Age ज्यादा practical है क्योंकि client clock mismatch का असर कम होता है। दोनों साथ हों तो Max-Age priority लेता है।
SameSite=Lax top-level safe navigation में Cookie भेज सकता है। इसलिए GET endpoint से data बदलना bug है। Strict ज्यादा strong है, पर email या external link से आने वाले flows को प्रभावित कर सकता है। None केवल वास्तविक cross-site जरूरत पर, और हमेशा Secure के साथ।
Consent boundary और use cases
Consent boundary वह रेखा है जहां service के लिए necessary cookies और analytics, ads, experiments वाले cookies अलग होते हैं। European Commission की cookies policy consent preference, authentication और analytics को अलग purposes के रूप में दिखाती है। यह legal advice नहीं है, पर engineering rule साफ है: authentication security को marketing consent से न जोड़ें।
Use case 1: SaaS login। __Host-session, short Max-Age, server-side revoke, CSRF token और हर login पर नया token रखें। Admin और billing screens पर SameSite=Strict या step-up verification जोड़ें।
Use case 2: content site। Free PDF, products और consultation CTA के लिए measurement helpful है, पर analytics reject करने पर download, purchase, login या inquiry form break नहीं होना चाहिए।
Use case 3: language और theme preferences। इन्हें JavaScript पढ़ सकता है, इसलिए ये HttpOnly न हों। लेकिन इनमें token, role, price या entitlement कभी न रखें।
Common failures
पहली गलती: __Host-session बिना Secure, Domain के साथ, या बिना Path=/। इससे prefix का security value खत्म हो जाता है।
दूसरी गलती: logout Cookie नहीं मिटाता क्योंकि Path या Domain अलग है।
तीसरी गलती: SameSite को पूरा CSRF solution मानना। Token, HTTP method और server validation अभी भी जरूरी हैं।
चौथी गलती: token को localStorage या client-readable Cookie में रखना। XSS के बाद token leak हो सकता है।
पांचवीं गलती: consent banner security cookies भी block कर देता है। Analytics reject करने से login, cart, checkout या CSRF protection disable नहीं होने चाहिए।
Prompt और verification
Claude Code को contract साफ दें:
Next.js App Router login cookie implement करें।
Requirements:
- cookie name: __Host-session
- attributes: HttpOnly, Secure, SameSite=Lax, Path=/, Max-Age
- Domain set न करें
- हर successful login पर नया session token generate करें
- logout में same Path और Max-Age=0 use करें
- analytics consent cookies को authentication cookies से mix न करें
- state-changing requests के लिए CSRF token explain करें
- MDN, Next.js और OWASP docs के against review करें
Login header check:
curl -i -X POST http://localhost:3000/api/login \
-H "Content-Type: application/json" \
-d '{"email":"masa@example.com","password":"correct-horse-battery-staple"}'
Expected:
Set-Cookie: __Host-session=...; Path=/; Max-Age=28800; HttpOnly; Secure; SameSite=Lax
Logout check:
curl -i -X POST http://localhost:3000/api/logout
Response में same name, Path=/ और Max-Age=0 होना चाहिए। Playwright में context.cookies() से httpOnly, secure, sameSite और expiry देखें।
Links, CTA और tested result
Authentication flow के लिए Claude Code authentication guide, JWT comparison के लिए JWT authentication article, और review के लिए security audit guide देखें। Official references: MDN Set-Cookie, Next.js cookies, OWASP Session Management, OWASP CSRF Prevention।
Reusable prompts, checklists और review templates के लिए ClaudeCodeLab products देखें। अगर team को real repository में consent, checkout और security review rules लागू करने हैं, तो training and consultation बेहतर next step है।
इस workflow को आजमाने पर सबसे बड़ा सुधार prompt में exact contract लिखने से आया: __Host-, logout scope, CSRF token और analytics consent boundary। केवल “cookies secure कर दो” लिखने पर Claude Code का output अभी भी manual review मांगता था।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code permission safety ladder: access धीरे-धीरे बढ़ाएं
read-only से limited edits, proof commands और deploy checks तक permission बढ़ाने की सुरक्षित ladder.
Claude Code Small PR Proof Pack: छोटे PR को review-ready बनाना
Claude Code PR के लिए diff, checks, public URL, CTA path और rollback वाला practical proof pack.
Claude Code Review Gate Before Commit: diff, test, public URL और CTA जांच
Claude Code से commit से पहले review gate बनाएं: diff, build, public URL, Gumroad, consultation, tests और unrelated files।