Skip to content
Rabat, Morocco
Posts

Stop Doing This in Next.js: 10 Common Mistakes (and What To Do Instead)

December 12, 2025
Stop Doing This in Next.js: 10 Common Mistakes (and What To Do Instead)
You know that feeling when a Next.js app is technically working… but somehow it’s still slow, your caching is unpredictable, and every “small change” turns into a multi-file ritual? That usually isn’t because Next.js is complicated. It’s because of a handful of habits people bring from older React/SPA patterns, habits that fight the way modern Next.js (App Router + Server Components) is designed to work. Here are 10 mistakes I see over and over, and what to do instead.
You need a click handler on one button… so you mark the entire page as a Client Component.
  • You ship more JavaScript than you need.
  • You lose server-only benefits (better streaming, smaller bundles, safer data access).
  • You start dragging server-only code into the browser by accident.
  • Default to Server Components.
  • Create small “islands” of interactivity as Client Components.
// app/products/page.tsx (Server Component by default)
import AddToCartButton from "./AddToCartButton";

export default async function ProductsPage() {
  const products = await fetch("https://example.com/api/products").then((r) =>
    r.json()
  );

  return (
    <div>
      {products.map((p: any) => (
        <div key={p.id}>
          <h2>{p.name}</h2>
          <AddToCartButton productId={p.id} />
        </div>
      ))}
    </div>
  );
}
// app/products/AddToCartButton.tsx
"use client";

export default function AddToCartButton({ productId }: { productId: string }) {
  return (
    <button onClick={() => console.log("add", productId)}>Add to cart</button>
  );
}

The page renders empty, then useEffect runs, then you fetch, then you render again.
  • Slower first paint.
  • More loading states.
  • More client-side complexity for something that could be server-rendered.
Fetch on the server whenever possible.
// Server Component
export default async function Page() {
  const data = await fetch("https://example.com/api/stats").then((r) =>
    r.json()
  );
  return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
If you need multiple requests, don’t accidentally serialize them:
// Parallel fetching
export default async function Dashboard() {
  const [user, notifications] = await Promise.all([
    fetch("https://example.com/api/me").then((r) => r.json()),
    fetch("https://example.com/api/notifications").then((r) => r.json()),
  ]);

  return (
    <div>
      <h1>Hi {user.name}</h1>
      <p>You have {notifications.length} notifications</p>
    </div>
  );
}

You change a fetch option, something caches (or doesn’t), and you don’t really know why.
  • Stale content that won’t update.
  • Everything becomes dynamic and you lose the performance benefits.
  • You can’t reason about production behavior.
Be explicit about freshness.
// Always fresh
await fetch("https://example.com/api/live", { cache: "no-store" });

// Cacheable (static-ish)
await fetch("https://example.com/api/content", { cache: "force-cache" });

// Cache with time-based revalidation
await fetch("https://example.com/api/blog", {
  next: { revalidate: 60 },
});
And when a route must be dynamic (e.g. depends on cookies/auth), say it:
// app/account/page.tsx
export const dynamic = "force-dynamic";

Importing server utilities into a Client Component, or using secret env vars in client code. If the browser can see it, it’s not a secret. Period.
  • Keep DB access / secret API calls in Server Components, Route Handlers, or Server Actions.
  • Only expose public env vars intentionally.
// Server-only usage
export default async function Page() {
  const secret = process.env.SECRET_API_KEY; // safe here
  const data = await fetch("https://example.com/private", {
    headers: { Authorization: `Bearer ${secret}` },
  }).then((r) => r.json());

  return <div>{data.message}</div>;
}

Doing heavy auth checks, DB calls, or trying to proxy requests inside middleware.
  • Middleware is designed to be fast and lightweight.
  • Heavy work there becomes global latency.
Use a proxy route (Route Handler) when you need to forward requests securely, add headers, hide secrets, or normalize responses. Keep middleware for truly tiny edge concerns (like simple redirects), not as a mini-backend. If all you need is simple pass-through routing (no auth, no secrets, no response shaping), prefer a platform-level proxy or rewrites instead of pushing logic into middleware.
// app/api/proxy/products/route.ts
import { NextResponse } from "next/server";

export async function GET(req: Request) {
  const url = new URL(req.url);
  const search = url.searchParams.toString();

  // Keep secrets on the server
  const upstream = `https://example.com/api/products${search ? `?${search}` : ""}`;
  const res = await fetch(upstream, {
    headers: {
      Authorization: `Bearer ${process.env.SECRET_API_KEY}`,
    },
  });

  const data = await res.json();
  return NextResponse.json(data, { status: res.status });
}

Client state for every input, manual loading flags, custom fetch calls, and duplicated validation. You’re writing a lot of code to replicate what the platform already does. Use HTML forms + Server Actions when it fits.
// app/contact/actions.ts
"use server";

export async function submitContact(formData: FormData) {
  const email = String(formData.get("email") || "");
  const message = String(formData.get("message") || "");

  if (!email.includes("@") || message.length < 10) {
    throw new Error("Please provide a valid email and a longer message.");
  }

  // Save to DB / send email (server-side)
}
// app/contact/page.tsx
import { submitContact } from "./actions";

export default function ContactPage() {
  return (
    <form action={submitContact}>
      <input name="email" placeholder="you@domain.com" />
      <textarea name="message" placeholder="Your message..." />
      <button type="submit">Send</button>
    </form>
  );
}

Using plain img tags everywhere, or using Next Image without a proper sizes value.
  • Big downloads.
  • Layout shift.
  • Slower LCP (often your biggest SEO/perf metric).
Use Next Image with intentional sizing.
import Image from "next/image";

export function Hero() {
  return (
    <Image
      src="/images/hero.jpg"
      alt="Product screenshot"
      width={1600}
      height={900}
      priority
      sizes="(max-width: 768px) 100vw, 900px"
    />
  );
}

Hardcoded title tags in random components, missing OG images, or generic metadata for every page. Your content might be great… but it won’t look great in search results or when shared. Use Next’s metadata APIs and generate per-route metadata.
// app/blog/[slug]/page.tsx
import type { Metadata } from "next";

export async function generateMetadata({
  params,
}: {
  params: { slug: string };
}): Promise<Metadata> {
  const post = await fetch(`https://example.com/api/posts/${params.slug}`).then(
    (r) => r.json()
  );

  return {
    title: post.title,
    description: post.summary,
    openGraph: {
      title: post.title,
      description: post.summary,
      images: [post.ogImageUrl],
    },
  };
}

One giant spinner for the whole app, or try/catch everywhere, or 404s handled inconsistently. Users feel latency more than they need to. Let routing segments own UX:
  • loading.tsx for instant skeletons
  • error.tsx for local error boundaries
  • not-found.tsx for clean 404s
// app/blog/[slug]/loading.tsx
export default function Loading() {
  return <p>Loading post…</p>;
}

Returning inconsistent responses, skipping validation, and mixing concerns until it’s impossible to evolve. Your app becomes a pile of endpoints with no contract. Make Route Handlers predictable: validate input, return typed JSON, handle errors intentionally.
// app/api/subscribe/route.ts
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  const body = await req.json().catch(() => null);
  const email = body?.email;

  if (typeof email !== "string" || !email.includes("@")) {
    return NextResponse.json({ error: "Invalid email" }, { status: 400 });
  }

  // Save subscription...
  return NextResponse.json({ ok: true });
}

If you take nothing else away, take this: Render on the server by default. Ship client JavaScript only where it earns its keep. That single mindset shift prevents bloated bundles, reduces data-fetching hacks, makes caching easier to reason about, and keeps secrets where they belong. If you want, tell me what you’re building (blog, SaaS, ecommerce, portfolio) and where it feels slow or confusing. I can recommend a caching + component boundary strategy that fits your app instead of generic advice.

Enjoyed this blog?

Seriously, thank you for spending your time here. If you made it to the end, you’re the kind of person who cares about craft, not just quick fixes.If you’d like to support my work, pick one (no pressure). It genuinely helps me keep writing and improving these blogs.
Subscribe to get a heads-up when I publish the next one. I keep it low-volume, and I only send what I’d personally want to read.

Subscribe to Josias's Newsletter

I occasionally write about software engineering, technology, and share thoughts on innovation and engineering.
One last thing: if you know someone who’d benefit from this, sharing it with them is one of the best compliments you can give. I appreciate you.