Skip to content
Frontend & UIChapter 41 / 57Intermediate7 min read

Next.js Practices

Next.js best practices Next.js 16 ke liye, server-first rendering, thin route handlers aur server actions, src/lib service layer, proxy.ts, use cache, config aur testing.

On this page

1. Yeh practice kya hai?

Yeh chapter Next.js ka framework layer hai. Component aur hook ke rules React Component Practices mein hain. Yahan sawal hai: code server par chale ya client par, data kahan se aaye, aur Next.js 16 ke naye tools (proxy.ts, async params, "use cache") kaise sahi jagah lagein.

2. Kyun zaroori hai?

Asli masle jo Next.js projects mein baar baar aate hain:

  • Poora page "use client" bana diya gaya. Bundle bara hua, data useEffect se aaya, aur pehla paint khali skeleton.
  • Ek module jo secret key parhta tha, ghalti se client component ne import kiya. Agar server-only laga hota to build wahin fail hota.
  • middleware.ts (ab proxy.ts) ko auth ki akeli diwar samjha gaya. Matcher ki ek ghalti se ek API route bina auth ke khula reh gaya.
Client-first aur fat routesServer-first aur thin routes
Page client component, bara bundlePage server component, sirf leaf client
useEffect se fetch, loading flashServer par data, HTML ke saath
Secret wala module client mein import ho saktaserver-only import se build fail
Proxy hi security, ek matcher ghalti se sab khulaHar page aur route khud caller check kare
Route handler mein queries aur rulesHandler patla, logic src/lib mein

3. Kab follow karein?

LevelKitna zarooriKyun
Learning projectServer aur client components ka farq samajhna, params await karnaYeh Next.js ka bunyadi mental model hai
Production codeSab lazmi: thin handlers, server-only, env module, security headers, endpoint testsPerformance aur security dono yahin tay hote hain
Senior levelCaching strategy aur boundaries design karna"use cache" ghalat jagah lage to ek user ka data doosre ko dikh sakta hai

4. Bura vs acha code

Bura: client page, secret aur sync params

tsx
"use client";

import { useEffect, useState } from "react";

export default function PostPage({ params }: { params: { slug: string } }) {
  const [post, setPost] = useState<Post | null>(null);

  useEffect(() => {
    fetch(`/api/posts/${params.slug}`).then((response) => response.json()).then(setPost);
  }, [params.slug]);

  return <article>{post?.body}</article>;
}

Next.js 16 mein params ek Promise hai, sync access nahi chalta. Aur poora page client par hai bina kisi wajah ke.

Acha: server page, cached service, thin handler

tsx
import { notFound } from "next/navigation";

import { PostView } from "@/components/PostView/PostView";
import { find } from "@/lib/posts/posts";

export default async function PostPage({ params }: PageProps<"/blog/[slug]">) {
  const { slug } = await params;
  const post = await find(slug);

  if (!post) {
    notFound();
  }

  return <PostView post={post} />;
}
ts
import "server-only";

import { cacheLife, cacheTag } from "next/cache";

import { db } from "@/lib/db";

export async function find(slug: string) {
  "use cache";
  cacheLife("hours");
  cacheTag(`post-${slug}`);

  return db.post.findUnique({ where: { slug } });
}

Comment banane ka route handler bhi wahi chaar steps karta hai:

ts
import { NextResponse } from "next/server";

import { requireUser } from "@/lib/auth/auth";
import { create } from "@/lib/comments/comments";
import { INVALID_COMMENT, createCommentSchema } from "@/lib/comments/comments.types";
import { limit } from "@/lib/rate-limit/rate-limit";

export async function POST(request: Request, { params }: RouteContext<"/api/posts/[id]/comments">) {
  const user = await requireUser();
  await limit(user.id);
  const { id } = await params;
  const parsed = createCommentSchema.safeParse(await request.json());

  if (!parsed.success) {
    return NextResponse.json({ error: INVALID_COMMENT }, { status: 422 });
  }

  return NextResponse.json(await create(user.id, id, parsed.data), { status: 201 });
}

Farq kya hai?

CheezBuraAcha
RenderingPoora page clientServer page, PostView agar zaroorat ho to client leaf
paramsSync accessawait params
DatauseEffect se, flashService se, "use cache" ke saath
Secret safetyKoi guard nahiserver-only import
Handler ki shapeKoi tay shape nahiAuth, rate limit, parse, ek call, respond

5. Kaise apply karein?

Next.js feature ka flow
Page server component, await params
Data src/lib service se, server-only ke saath
Public aur shared data par use cache, cacheTag
Mutation route handler ya server action se, dono patle
Write ke baad updateTag ya refresh
Endpoint test tests/api mein
AreaPractice
proxy.tsSirf ek kaam: session refresh ya redirect. Security har page aur handler mein
Route handler vs server actionData APIs ke liye route handler, ek page ke form ke liye server action. Ek resource ke liye dono nahi
Private pagesMetadata mein robots: { index: false }
Finite slugsgenerateStaticParams ke saath dynamicParams = false, anjaan slug 404
next.config.tsSecurity headers (CSP, nosniff, HSTS), images.remotePatterns mein exact hosts, cacheComponents: true
tsconfig.jsonstrict: true, @/* alias src/* par
Envsrc/lib/env.ts ka requireEnv(), kabhi process.env.X! nahi
Node APIsHandler par export const runtime = "nodejs", lambe kaam par maxDuration
TestsVitest. tests/api mein seeded user ke saath endpoint tests, tests/lib mein pure tests, server-only ko stub par alias

6. Exceptions aur common mistakes

"use cache" sirf us data par jo sab users ke liye same ho. User-specific data ko shared cache mein dalna data leak hai.

"Route handler ya server action" par teams kaafi mukhtalif hain. Bohat si teams saari mutations server actions se karti hain aur yeh Next.js ka promoted rasta bhi hai. Yahan ka sakht rule data APIs ko route handlers mein rakhta hai kyunki unhe mobile app, cron aur tests bhi seedha HTTP se call kar sakte hain. Trade-off: server actions kam boilerplate, route handlers zyada reusable. Jo bhi chuno, ek resource ke liye ek hi.

Galati: Page ya layout par use client lagana

Why? Poora tree client bundle mein chala jata hai aur server par data lane ka faida khatam.

Behtar: Sirf us chhote leaf par use client lagao jise state, effect ya browser API chahiye.

Galati: proxy.ts ko akeli security diwar samajhna

Why? Matcher ki ek ghalti ya naya route jo matcher se bahar ho, bina auth ke khul jata hai.

Behtar: Har page aur route handler khud caller resolve kare. Proxy sirf session refresh ya redirect.

Galati: Server action ke andar query aur business rules

Why? Server action bhi ek controller hai. Rules wahan phans gaye to cron aur API unhe reuse nahi kar sakte.

Behtar: Action bhi auth, parse, ek service call aur updateTag. Rule src/lib mein.

7. Pehle aur baad mein kya seekhein?

Suggested order
Server & Client Components
Service Layer & Thin Controllers
Next.js Practices
Endpoint Tests First

Final quick revision

CheckHaan / Nahi
Page aur layout server componentsHaan
params aur searchParams awaitHaan
Secret wale modules mein server-onlyHaan
Handler: auth, rate limit, parse, ek call, respondHaan
User-specific data par "use cache"Nahi
proxy.ts akeli securityNahi
process.env.X!Nahi, requireEnv()