Caching ও Revalidation
use cache directive, cacheLife, cacheTag, revalidateTag/updateTag — আধুনিক caching বাংলায়।
Caching হলো data fetch-এর ফলাফল সংরক্ষণ করা যাতে বারবার একই কাজ না করতে হয়। Next.js-এ Cache Components (Next 15.3+/16) দিয়ে সহজ caching হয়।
Cache Components চালু করা
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
cacheComponents: true,
};
export default nextConfig;use cache হুড
"use cache" directive দিয়ে একটি async function বা component-এর ফলাফল cache করা যায়, cacheLife() দিয়ে lifetime ঠিক করা যায়।
import { cacheLife } from "next/cache";
export async function getUsers() {
"use cache";
cacheLife("hours");
return db.query("SELECT * FROM users");
}import { cacheLife } from "next/cache";
export default async function Page() {
"use cache";
cacheLife("hours");
const users = await db.query("SELECT * FROM users");
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}cacheLife Profiles
| Profile | Stale | Revalidate | Expire |
|---|---|---|---|
| seconds | 0 | 1s | 60s |
| minutes | 5m | 1m | 1h |
| hours | 5m | 1h | 1d |
| days | 5m | 1d | 1w |
| weeks | 5m | 1w | 30d |
| max | 5m | 30d | ~indefinite |
Revalidation (cache হারিয়ে গেলে)
cacheTag('posts')— cached data-তে tag দিনrevalidateTag('posts')— on-demand invalidate (Route Handler/Server Action)updateTag('posts')— এখনই expire (read-your-own-writes)revalidatePath('/posts')— path-based invalidate
"use server";
import { updateTag } from "next/cache";
import { redirect } from "next/navigation";
export async function createPost(formData: FormData) {
const post = await db.post.create({
data: { title: formData.get("title") },
});
updateTag("posts");
redirect(`/posts/${post.id}`);
}updateTag Server Actions-এ — user-এর নিজের লেখা এখনই দেখায়। revalidateTag Server Action ও Route Handler উভয়ে — stale-while-revalidate (background refresh)। Tag-based revalidation path-based-এর চেয়ে বেশি precise, সুতরাং পছন্দ করুন।
যে data runtime-data-এর উপর নির্ভর করে না ও কিছু সময় পুরোনো রাখা চলবে, তাই use cache + cacheLife দিন। Content-শোর জন্য tag + длинный cache ব্যবহার করে mutation-এ revalidate করুন।