Skip to content
BackendChapter 23 / 34Advanced5 min read

Authentication

Next.js authentication Better Auth ya Auth.js ke saath, session cookies, Data Access Layer checks aur proxy ke optimistic redirect ka sahi tareeqa.

On this page

1. Authentication kya hai?

Next.js mein auth teen hisson mein samjhein:

HissaKaam
AuthenticationLogin: email password, Google, GitHub waghera
Session managementLogin ke baad har request par user ko yaad rakhna, aksar httpOnly cookie se
AuthorizationHar page, Server Action aur Route Handler mein permission check

Khud se poora auth likhna mushkil aur risky hai. Is liye Better Auth ya Auth.js jaisi library use karein jo sessions, OAuth aur password hashing sambhal leti hai.

2. Kyun zaroori hai?

Sirf proxy ya layout mein checkData Access Layer ke saath
Proxy sirf cookie ki maujoodgi dekhta haiDAL har dafa session verify karta hai
Server Action seedha call ho kar bypassHar action mein verifySession
Layout navigation par dobara nahi chaltaCheck data ke bilkul paas
Har jagah alag auth logicEk file, ek jagah se sab checks

3. Kahan use hota hai?

JagahKya check karein
proxy.tsOptimistic redirect: cookie nahi to /login
Server Component pageverifySession() phir user ka data
Server ActionSession + ownership, mutation se pehle
Route HandlerSession na ho to 401, role galat to 403
Client ComponentSirf UI dikhana ya chhupana, security nahi

4. Kaise kaam karta hai?

Login se protected data tak
User login form submit karta hai
Auth library credentials ya OAuth verify karti hai
httpOnly session cookie set
proxy optimistic redirect karta hai
DAL session verify karta hai
Sirf zaroori data return

5. Code example

Step 1: Better Auth setup

ts
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { nextCookies } from "better-auth/next-js";
import { db } from "@/lib/db";

export const auth = betterAuth({
  database: prismaAdapter(db, { provider: "postgresql" }),
  emailAndPassword: { enabled: true },
  socialProviders: {
    github: {
      clientId: process.env.GITHUB_CLIENT_ID as string,
      clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
    },
  },
  plugins: [nextCookies()],
});

app/api/auth/[...all]/route.ts mein library ka handler lagayein:

ts
import { toNextJsHandler } from "better-auth/next-js";
import { auth } from "@/lib/auth";

export const { GET, POST } = toNextJsHandler(auth);

Step 2: Data Access Layer

ts
import "server-only";
import { cache } from "react";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";

export const getSession = cache(async () => {
  return auth.api.getSession({ headers: await headers() });
});

export async function verifySession() {
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }
  return { userId: session.user.id, name: session.user.name };
}

Step 3: Page aur Server Action mein use

tsx
import { verifySession } from "@/lib/dal";
import { db } from "@/lib/db";

export default async function DashboardPage() {
  const { userId, name } = await verifySession();
  const orders = await db.order.findMany({ where: { userId } });

  return (
    <main>
      <h1>Khush aamdeed, {name}</h1>
      <p>Aapke orders: {orders.length}</p>
    </main>
  );
}

Code kaise kaam kar raha hai?

CheezMatlab
betterAuth({...})Auth config: email password aur GitHub login
prismaAdapter(db, ...)Users aur sessions database mein store
nextCookies()Server Actions mein login par cookie set karne ke liye plugin
toNextJsHandler(auth)/api/auth/... ke saare endpoints
auth.api.getSession({ headers })Cookie se session validate
cache(...)Ek render pass mein session sirf ek dafa fetch
verifySession()Session nahi to redirect, warna sirf zaroori fields
where: { userId }User sirf apna data dekhe

Auth.js (NextAuth v5) bhi isi pattern par chalta hai: auth.ts se auth() function milta hai jo DAL mein session deta hai. Library jo bhi ho, DAL wala pattern same rehta hai.

Interview tip

"Kya proxy.ts mein auth check kaafi hai?" Jawab: nahi. Proxy sirf cookie dekhta hai, validate nahi karta. Server Actions aur Route Handlers public endpoints hain, is liye unke andar bhi verifySession() zaroori hai.

6. Common mistakes

Galati: Sirf proxy.ts par auth ka bharosa karna

Why? Cookie ki maujoodgi validation nahi hai, aur actions ya API ko seedha call kar ke bypass ho sakta hai.

Behtar: Proxy ko sirf redirect ke liye rakho, har data access par DAL se session verify karo.

Galati: Layout mein auth check kar ke pages ko safe samajhna

Why? Layouts navigation par dobara render nahi hote aur nested segments alag se bhi chal sakte hain.

Behtar: Check page, Server Action aur data function ke qareeb karo.

Galati: Poora user object Client Component ko bhej dena

Why? Password hash ya private fields browser tak pohanch sakte hain.

Behtar: DAL se sirf woh fields return karo jo UI ko chahiye.

Galati: Server Action mein ownership check bhool jana

Why? Logged in user kisi aur ka record id bhej kar delete ya edit kar sakta hai.

Behtar: Query mein userId shamil karo taake user sirf apna data badal sake.

7. Pehle aur baad mein kya seekhein?

Final quick revision

PointDetail
LibraryBetter Auth ya Auth.js
SessionhttpOnly cookie, server par validate
ProxySirf optimistic redirect
DALverifySession() har page, action aur handler mein
DataSirf zaroori fields return, userId se filter