অধ্যায় ০৭ / ১৮Frontend

Next.js (App Router)

App Router, rendering, caching আর Server Actions।

Next.js হলো React এর উপর full stack framework: routing, server rendering, API, caching আর deployment এক জায়গায়। এখনকার standard হলো App Router (app/ folder); পুরনো Pages Router (getServerSideProps) অনেক legacy project এ এখনো আছে, তাই দুটোর ধারণা থাকা ভালো। (Version নোট: Next.js 16 পর্যন্ত তথ্য; নতুন release এ কিছু API বদলাতে পারে, তাই official docs মিলিয়ে নিও।)

File-based routing

Fileকাজ
app/page.tsxRoute এর UI
layout.tsxShared layout, navigation এ re-render হয় না
loading.tsxSuspense fallback (streaming)
error.tsxError boundary (client component)
not-found.tsx404
route.tsAPI endpoint (GET, POST ইত্যাদি export করো)
[slug], [...slug]Dynamic আর catch-all segment
(group)URL এ না এসে folder সাজানো
@slot, (.)photoParallel route, intercepting route (modal)

Server Components vs Client Components

App Router এ component by default Server Component: server এ render হয়, সরাসরি database পড়তে পারে, browser এ কোনো JS পাঠায় না। State, effect, event handler বা browser API লাগলে file এর উপরে "use client" লিখতে হয়।

  • "use client" যত নিচে (leaf) রাখা যায় তত কম JS পাঠাতে হয়।
  • Server Component থেকে Client Component এ props serializable হতে হবে (function পাঠানো যায় না, Server Action ছাড়া)।
  • Client Component এর ভেতরে Server Component import করা যায় না, কিন্তু children হিসেবে পাঠানো যায়।
  • Secret বা DB code client এ যাওয়া আটকাতে import "server-only"।
tsx
// app/products/[id]/page.tsx  (Server Component)
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const product = await db.product.findUnique({ where: { id } });
  if (!product) notFound();
  return <ProductView product={product} />;
}

Rendering strategy

Strategyকখন HTML তৈরি হয়উপযুক্ত
SSG (Static)Build time এBlog, docs, marketing page
ISR / revalidateBuild এ, তারপর নির্দিষ্ট সময় পরপর বা on-demandProduct page, news
SSR (Dynamic)প্রতিটা request এPersonalized dashboard
StreamingRequest এ, অংশ অংশ করে (Suspense)ধীর data আছে এমন page
Partial PrerenderingStatic shell + dynamic holeStatic আর personalized মিশ্র page
CSRBrowser এHighly interactive widget

Caching

Next.js caching সবচেয়ে confusing topic, আর version অনুযায়ী বদলেছে। Next.js 15 থেকে fetch default এ cache হয় না; Next.js 16 এ Cache Components আসে, যেখানে "use cache" directive দিয়ে explicitly বলতে হয় কোন function/component cache হবে।

  • Time-based: revalidate বা cacheLife("hours")।
  • On-demand: data বদলালে revalidateTag("products") বা revalidatePath("/products")।
  • Client Router Cache: আগে দেখা route এ back navigation instant হয়।
  • Interview এ বলো: "কোন data কতটা stale হতে পারে, সেটা আগে ঠিক করি, তারপর cache আর invalidation বেছে নিই।"

Server Actions

Form submit বা mutation এর জন্য আলাদা API লিখতে হয় না; "use server" function সরাসরি form থেকে call করা যায়।

ts
"use server";
export async function createPost(prev: State, formData: FormData) {
  const session = await auth();              // সবসময় auth check
  if (!session) return { error: "Unauthorized" };
  const parsed = PostSchema.safeParse(Object.fromEntries(formData)); // সবসময় validate
  if (!parsed.success) return { error: "Invalid input" };
  await db.post.create({ data: { ...parsed.data, authorId: session.user.id } });
  revalidatePath("/posts");
  return { ok: true };
}

Server Action আসলে একটা public POST endpoint। তাই প্রতিটা action এ authentication, authorization আর input validation করতেই হবে।

Middleware/Proxy, Auth আর অন্যান্য

  • Middleware (Next.js 16 এ নাম proxy.ts): request route এ পৌঁছানোর আগে চলে; redirect, rewrite, locale, হালকা auth check। এখানে ভারী DB কাজ করো না, আর এটাকেই একমাত্র auth layer বানিও না।
  • Auth: Auth.js (NextAuth), Better Auth, Clerk। Data পড়ার জায়গায় (data access layer) আবার session check করো।
  • Optimization: next/image (resize, lazy, WebP/AVIF), next/font (layout shift ছাড়া font), next/link (prefetch), Metadata API (SEO)।
  • Environment variable: NEXT_PUBLIC_ prefix থাকলে browser এ যায়; secret এ এই prefix কখনো না।
  • Deployment: Vercel সবচেয়ে সহজ; self-host এ output: "standalone" + Docker; static export এর জন্য output: "export"।

Next.js নাকি আলাদা backend?

Next.js এর route handler আর Server Action ছোট-মাঝারি app এর জন্য যথেষ্ট। Mobile app ও একই API ব্যবহার করলে, লম্বা background job লাগলে, বা আলাদা backend team থাকলে NestJS/FastAPI এর মতো আলাদা backend ভালো।

Interview প্রশ্ন

  • SSR, SSG, ISR, CSR এর পার্থক্য আর কখন কোনটা?
  • Server Component আর Client Component এর পার্থক্য কী? কখন "use client" লাগে?
  • Hydration কী? Hydration mismatch error কেন হয়? (server আর client এ আলাদা HTML, যেমন Date.now())
  • Product এর দাম বদলালে cached page কীভাবে update করবে?
  • Server Action এ security এর জন্য কী কী খেয়াল রাখবে?

এই অধ্যায় পড়া শেষ?

পড়া শেষ চিহ্নিত করো, নিজের অগ্রগতি ধরে রাখো।