Skip to content
MiraiTech
All writing
Full stack

· 9 min read

How we organize large Next.js codebases

How we organize routes and features in large Next.js apps, where the server and client boundary goes, data fetching, middleware, and what we got wrong at first.

The problem with the default structure

Every Next.js tutorial starts the same way: a few pages, a components folder, maybe a lib directory. That works until the application passes about 50 routes and 30 contributors. After that, merge conflicts multiply and the shared components folder turns into a dumping ground where nobody can find anything.

At MiraiTech we have built everything from marketing sites to full SaaS platforms on Next.js. These are the patterns that held up on the large ones.

Organizing routes

Route groups by feature

Route groups (folders in parentheses) are the most useful organizing tool we have for large apps. They let you colocate related routes without changing the URL structure.

app/
  (marketing)/
    page.tsx
    pricing/page.tsx
    blog/[slug]/page.tsx
    layout.tsx          # marketing-specific layout with nav
  (dashboard)/
    dashboard/page.tsx
    dashboard/settings/page.tsx
    dashboard/projects/[id]/page.tsx
    layout.tsx          # authenticated layout with sidebar
  (auth)/
    login/page.tsx
    register/page.tsx
    layout.tsx          # minimal layout, no nav

Each group gets its own layout, loading states and error boundaries, so a crash in the dashboard stays out of the marketing pages.

Parallel routes for complex layouts

Some pages have sections that should load independently, such as a dashboard with a feed, a notifications panel and an analytics widget. Parallel routes stop one slow query from blocking the whole page.

app/(dashboard)/dashboard/layout.tsx
export default function DashboardLayout({
  children,
  feed,
  notifications,
  analytics,
}: {
  children: React.ReactNode
  feed: React.ReactNode
  notifications: React.ReactNode
  analytics: React.ReactNode
}) {
  return (
    <div className="grid grid-cols-12 gap-6">
      <main className="col-span-8">{children}</main>
      <aside className="col-span-4 space-y-6">
        <Suspense fallback={<NotificationsSkeleton />}>
          {notifications}
        </Suspense>
        <Suspense fallback={<AnalyticsSkeleton />}>
          {analytics}
        </Suspense>
      </aside>
      <section className="col-span-12">
        <Suspense fallback={<FeedSkeleton />}>
          {feed}
        </Suspense>
      </section>
    </div>
  )
}

Server and client boundaries

The biggest performance wins, and the most confusing bugs, come from where you put the server/client boundary.

Where to put the boundary

Push "use client" as far down the component tree as possible. Most of the tree should stay as Server Components, with Client Components only where you need interactivity.

components/project-card.tsx
// This is a Server Component — no directive needed
import { getProject } from "@/lib/data"
import { ProjectActions } from "./project-actions"
 
export async function ProjectCard({ id }: { id: string }) {
  const project = await getProject(id)
 
  return (
    <article className="rounded-lg border p-6">
      <h3 className="text-lg font-semibold">{project.name}</h3>
      <p className="mt-2 text-muted-foreground">{project.description}</p>
      <div className="mt-4 flex items-center gap-2 text-sm text-muted-foreground">
        <span>{project.language}</span>
        <span>·</span>
        <span>{project.stars} stars</span>
      </div>
      {/* Only this small piece needs client-side JS */}
      <ProjectActions projectId={id} initialStarred={project.isStarred} />
    </article>
  )
}

Data fetching

Request deduplication with cache

Next.js deduplicates fetch calls within the same render pass automatically. Calls through an ORM or database client are not covered, so you have to handle those yourself.

lib/data.ts
import { cache } from "react"
import { db } from "@/lib/db"
 
// Deduplicated within a single request
export const getProject = cache(async (id: string) => {
  return db.project.findUnique({
    where: { id },
    include: { members: true, tags: true },
  })
})
 
// Revalidation-aware fetching
export const getProjects = cache(async (teamId: string) => {
  return db.project.findMany({
    where: { teamId },
    orderBy: { updatedAt: "desc" },
  })
})

Caching strategy by data type

Data typeCache strategyRevalidationWhy
User profileNo cacheN/AMust always be fresh after mutations
Project listTime-based60 secondsTolerable staleness, high read volume
Blog contentOn-demandWebhook from CMSInfrequent changes, cache indefinitely
AnalyticsTime-based300 secondsExpensive query, approximate data acceptable
Static assetsImmutableNeverContent-hashed filenames handle versioning

Middleware

Middleware runs on every request before routing, so a slow middleware function adds latency to every page load.

Keep middleware thin

Our rule is that middleware handles only routing decisions and header manipulation. Authentication checks are fine. Database queries are not.

middleware.ts
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
 
export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl
 
  // Auth check via cookie — no database call
  const session = request.cookies.get("session")?.value
 
  if (pathname.startsWith("/dashboard") && !session) {
    return NextResponse.redirect(new URL("/login", request.url))
  }
 
  // A/B test routing via header
  const bucket = request.cookies.get("ab-bucket")?.value || assignBucket()
  const response = NextResponse.next()
  
  if (!request.cookies.get("ab-bucket")) {
    response.cookies.set("ab-bucket", bucket, { maxAge: 60 * 60 * 24 * 30 })
  }
 
  response.headers.set("x-ab-bucket", bucket)
  return response
}
 
export const config = {
  matcher: ["/dashboard/:path*", "/pricing"],
}

Organizing code by feature

In large apps we organize code by feature. Rather than one components/ folder with 200 files, each feature owns its components, hooks, utilities and types.

features/
  projects/
    components/
      project-card.tsx
      project-list.tsx
      create-project-dialog.tsx
    hooks/
      use-project-filters.ts
    actions/
      create-project.ts
      delete-project.ts
    types.ts
    constants.ts
  billing/
    components/
      plan-selector.tsx
      invoice-table.tsx
    actions/
      update-subscription.ts
    types.ts

Shared UI primitives (buttons, inputs, modals) live in a separate components/ui/ directory. If only one feature uses something, it stays in that feature's folder. Once two or more features need it, it moves to shared.

Performance

Streaming and Suspense

When a page needs several pieces of data that arrive at different speeds, wrap the slow sections in Suspense boundaries. Fast content renders right away and the slow parts stream in.

Bundle analysis

We run @next/bundle-analyzer on every PR that touches shared dependencies. A single unguarded import dayjs in a client component can add 70KB to the JavaScript bundle. An ESLint rule flags heavy library imports in files containing "use client".

Image optimization

The next/image component handles most cases. In a large app we also define standard aspect ratios and sizes for each context (cards, heroes, avatars) and enforce them with wrapper components that set the correct sizes props.

OptimizationImpactEffort
Server Components by default30-50% less JSLow (it is the default)
Route-level code splittingFaster initial loadsFree with App Router
Suspense boundariesBetter perceived performanceMedium (you have to design the loading states)
Bundle analysis CI checkPrevents regressionsLow (one-time setup)
Dynamic imports for heavy componentsSmaller initial bundleLow per component

What we got wrong at first

Our first large Next.js app got much of this wrong: huge client-side bundles from careless "use client" placement, a single global layout that re-rendered on every navigation, and no Suspense boundaries anywhere. Pages showed a blank screen for 3-4 seconds while every query resolved.

The refactor took three weeks. Largest Contentful Paint dropped from 4.2s to 1.1s, and our JavaScript bundle shrank by 60%.

Written by the MiraiTech team in Tokyo

If something here is wrong, or you are working on a similar problem, write to us at contact@mirai-tech.net.