Next.js / 15 min read

My Complete Next.js Folder Structure for Large Projects

Learn how to organize a scalable Next.js App Router project using route groups, feature folders, shared components, Supabase clients, and secure data access.

No reproducible test record has been approved for this published version. Check its commands against your software versions before using them.

How we verify guides
My Complete Next.js Folder Structure for Large Projects
On this page

Next.js Folder Structure for Large Projects (App Router Guide)

A Next.js project is easy to organize when it has three pages and a handful of components.

Then authentication, dashboards, billing, admin tools, and database operations arrive.

Suddenly, finding a component requires searching through several folders. Shared utilities become difficult to distinguish from feature-specific logic, and a small change can affect seemingly unrelated parts of the application.

A good folder structure makes those relationships easier to understand.

But there isn't one official architecture that every large Next.js application must follow.

The best approach is to use Next.js App Router conventions for routing, keep feature-specific code together, and introduce shared abstractions only when they're useful.

In this guide, we'll walk through a practical Next.js folder structure suitable for a growing application, explain where different files belong, and cover common organization mistakes.

The examples use TypeScript, the Next.js App Router, and optional Supabase integration.

1. A Practical Next.js Folder Structure

Here's a possible structure for a project with public pages, an authenticated dashboard, billing, and an admin section.

text
my-nextjs-app/
├── public/
│   └── images/
│
├── src/
│   ├── app/
│   │   ├── (marketing)/
│   │   │   ├── page.tsx
│   │   │   ├── blog/
│   │   │   │   ├── page.tsx
│   │   │   │   └── [slug]/
│   │   │   │       └── page.tsx
│   │   │   └── pricing/
│   │   │       └── page.tsx
│   │   │
│   │   ├── (workspace)/
│   │   │   ├── layout.tsx
│   │   │   ├── dashboard/
│   │   │   │   ├── page.tsx
│   │   │   │   ├── loading.tsx
│   │   │   │   └── _components/
│   │   │   │       └── StatsCard.tsx
│   │   │   └── settings/
│   │   │       └── page.tsx
│   │   │
│   │   ├── admin/
│   │   │   ├── layout.tsx
│   │   │   └── page.tsx
│   │   │
│   │   ├── api/
│   │   │   └── webhooks/
│   │   │       └── route.ts
│   │   │
│   │   ├── layout.tsx
│   │   ├── not-found.tsx
│   │   └── globals.css
│   │
│   ├── components/
│   │   ├── ui/
│   │   │   ├── Button.tsx
│   │   │   └── Input.tsx
│   │   └── shared/
│   │       ├── Navbar.tsx
│   │       └── UserMenu.tsx
│   │
│   ├── features/
│   │   ├── billing/
│   │   │   ├── components/
│   │   │   ├── actions.ts
│   │   │   └── queries.ts
│   │   └── inventory/
│   │       ├── components/
│   │       ├── actions.ts
│   │       └── queries.ts
│   │
│   ├── lib/
│   │   ├── auth/
│   │   │   └── require-user.ts
│   │   ├── supabase/
│   │   │   ├── client.ts
│   │   │   ├── server.ts
│   │   │   └── proxy.ts
│   │   └── utils.ts
│   │
│   ├── hooks/
│   ├── types/
│   ├── config/
│   └── proxy.ts
│
├── .env.local
├── package.json
├── next.config.ts
└── tsconfig.json

This is an architectural example, not a complete runnable starter template. The authentication helpers, page implementations, and feature modules still need to be created.

Not every project needs all these folders.

For a smaller application, starting with app, components, and lib may be enough.

2. Keep Routing Concerns Inside the App Directory

The app directory is the center of the Next.js App Router.

It defines routes through folders and special files such as:

  • page.tsx — the UI for a route.
  • layout.tsx — shared layout across a route segment.
  • loading.tsx — loading UI.
  • error.tsx — error boundary for a route segment.
  • not-found.tsx — UI for not-found states.
  • route.ts — a Route Handler, commonly used for HTTP endpoints.

Not every ordinary file inside app becomes a public route. Next.js uses special file conventions to determine which folders are publicly accessible.

Example: A simple dashboard route

tsx
// src/app/(workspace)/dashboard/page.tsx

import { StatsCard } from "./_components/StatsCard";

export default function DashboardPage() {
  return (
    <main>
      <h1>Dashboard</h1>
      <StatsCard title="Active Products" value={42} />
    </main>
  );
}

This is a deliberately simple display example; the value is sample data.

A real dashboard would retrieve authorized information from a server-side data-access function.

Should every page be under 100 lines?

Not necessarily.

A small page can become difficult to maintain if it contains unrelated business logic, while a longer page can remain readable when it primarily composes UI.

Instead of enforcing a strict line limit, ask:

  • Does this page contain reusable business logic?
  • Are database queries repeated elsewhere?
  • Is authorization happening in the correct place?
  • Would moving a section into another component make it easier to understand?

Keep page files focused on their route's responsibilities rather than chasing an arbitrary number of lines.

3. Use Route Groups Without Changing URLs

Route groups let you organize related pages without adding their folder names to the URL.

A route group is written using parentheses.

For example:

text
app/
├── (marketing)/
│   ├── page.tsx
│   └── pricing/
│       └── page.tsx
│
└── (workspace)/
    └── dashboard/
        └── page.tsx

These produce routes such as:

text
/
 /pricing
 /dashboard

The names (marketing) and (workspace) do not appear in the URL.

Why route groups are useful

They can separate public marketing pages from authenticated application pages.

You can also give route groups their own nested layouts.

For example, a workspace layout might display a sidebar while public pages use a wider, navigation-focused design.

Avoid route conflicts

Two route groups cannot define routes that resolve to the same URL.

For example:

text
app/(marketing)/about/page.tsx
app/(workspace)/about/page.tsx

Both would correspond to /about, creating a conflict.

Route groups organize the filesystem; they do not create separate URL namespaces.

Also, navigation between route groups with different root layouts can trigger a full page load. The example structure uses one top-level root layout.

4. Organize Components by Responsibility

A large components folder can become difficult to navigate when every component lives at the same level.

A practical approach is to distinguish between reusable UI, application-wide components, and feature-specific components.

Reusable UI components

text
components/
└── ui/
    ├── Button.tsx
    ├── Input.tsx
    ├── Dialog.tsx
    └── Badge.tsx

These are general building blocks.

A Button component should not need to understand inventory permissions or billing records.

Keeping UI primitives independent makes them easier to reuse.

Shared application components

text
components/
└── shared/
    ├── Navbar.tsx
    ├── UserMenu.tsx
    └── ThemeToggle.tsx

These components may know about application-level concepts but are used across multiple routes or features.

Route-specific components

Suppose a dashboard contains a statistics card used nowhere else.

You can colocate it with the dashboard:

text
app/
└── (workspace)/
    └── dashboard/
        ├── page.tsx
        └── _components/
            └── StatsCard.tsx

The underscore marks _components as a private folder under Next.js conventions.

This is useful for clearly separating colocated implementation files from route segments.

However, private folders are not a security mechanism. Authentication and data authorization must be implemented separately.

A useful decision rule

Ask yourself:

Would this component still make sense if its current feature were removed?

If yes, it might belong in a shared component directory.

If not, keep it close to the feature that owns it.

Don't move every component into a global folder just because two files import it.

5. Group Business Logic by Feature

For applications with multiple business domains, a features directory can reduce the distance between related files.

For example:

text
features/
├── billing/
│   ├── components/
│   │   └── BillingSummary.tsx
│   ├── actions.ts
│   └── queries.ts
│
└── inventory/
    ├── components/
    │   └── ProductTable.tsx
    ├── actions.ts
    └── queries.ts

Billing-specific code lives inside billing.

Inventory-specific code lives inside inventory.

This makes it easier to find the files related to a particular domain.

What belongs in a feature folder?

Depending on project size, a feature may own:

  • UI components
  • Server Actions
  • Database queries
  • Validation schemas
  • Types specific to the feature
  • Tests
  • Business rules

You don't need every subfolder from day one.

Start with the files you actually have.

Example: An inventory query

ts
// src/features/inventory/queries.ts

import "server-only";

import { createClient } from "@/lib/supabase/server";

export async function getProducts() {
  const supabase = await createClient();

  const {
    data: userData,
    error: authError,
  } = await supabase.auth.getUser();

  if (authError || !userData.user) {
    throw new Error("Authentication required");
  }

  const { data, error } = await supabase
    .from("products")
    .select("id, name, stock")
    .eq("owner_id", userData.user.id);

  if (error) {
    throw new Error("Unable to load products");
  }

  return data;
}

This example assumes you have implemented the cookie-aware Supabase server client and that your database schema contains the referenced fields.

The query also assumes properly configured Row Level Security policies.

Filtering by owner is useful, but it should not replace database-level authorization.

The server-only import helps prevent this data-access module from being imported into client-side code.

6. Put Authorization Close to the Data

One of the most important architectural decisions is where authentication and authorization checks happen.

A common pattern is to add a check inside a protected layout.

For example:

text
app/
└── (workspace)/
    ├── layout.tsx
    └── dashboard/
        └── page.tsx

The layout can display a navigation menu and render a user-specific shell.

But a layout check alone is not sufficient security.

Next.js layouts can preserve state across navigations and do not necessarily re-render for every navigation.

Therefore, a layout should not be your only authorization boundary.

A safer architecture

Centralize access checks in a server-side data-access layer.

For example:

text
lib/
└── auth/
    └── require-user.ts

A minimal helper using a properly configured Supabase server client could look like this:

ts
// src/lib/auth/require-user.ts

import "server-only";

import { createClient } from "@/lib/supabase/server";

export async function requireUser() {
  const supabase = await createClient();

  const { data, error } =
    await supabase.auth.getUser();

  if (error || !data.user) {
    throw new Error("Authentication required");
  }

  return data.user;
}

This checks that the current request has an authenticated user.

It does not automatically determine whether that user is an administrator, an organization member, or the owner of a particular record.

Those permissions require additional authorization logic.

Protect each operation

Server Actions and Route Handlers can be invoked independently of your page layout.

For sensitive operations, validate the caller and their permissions inside the operation or the data-access function it uses.

For Supabase applications, enforce appropriate Row Level Security policies in the database as well.

A hidden button or protected-looking layout does not make an API operation secure.

7. Keep Supabase Browser and Server Clients Separate

When using Supabase with the Next.js App Router, browser-side and server-side code operate in different environments.

They should use the appropriate Supabase clients.

A common structure is:

text
lib/
└── supabase/
    ├── client.ts
    ├── server.ts
    └── proxy.ts

Here:

  • client.ts creates a Supabase client for browser components.
  • server.ts creates a cookie-aware client for Server Components, Server Actions, and Route Handlers.
  • proxy.ts contains shared session-refresh logic used by the Next.js request-level entry point.

Why not use one universal client?

Browser components and server-side code have different access to cookies and request context.

Keeping their implementations separate makes those boundaries easier to reason about.

It also reduces the chance of accidentally importing server-only behavior into browser code.

Next.js 16: Proxy versus Middleware

With Next.js 16, the request-level convention was renamed from middleware.ts to proxy.ts.

For the structure shown in this guide:

text
src/proxy.ts

is the Next.js entry point.

The separate file:

text
src/lib/supabase/proxy.ts

is an ordinary helper module, not a special Next.js entry point.

It may contain the session-update function imported by the main proxy.

For earlier supported Next.js versions that use Middleware, follow their corresponding file convention and Supabase SSR instructions.

Important security reminder

Never expose a Supabase secret or service-role key through a browser client.

Use public/publishable credentials in the intended browser environment and keep privileged credentials on trusted servers.

Even on the server, avoid bypassing RLS for ordinary user operations.

8. Use Path Aliases Instead of Deep Relative Imports

Deeply nested relative imports can make moving files unnecessarily tedious.

For example:

ts
import { formatPrice } from "../../../../lib/utils";

A path alias gives you a more readable alternative:

ts
import { formatPrice } from "@/lib/utils";

If your application uses a src directory, a typical TypeScript configuration is:

json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}

The file is tsconfig.json.

You should merge these options into your existing TypeScript configuration rather than replacing the entire configuration file.

A project generated with create-next-app may already include a suitable alias.

Path aliases improve import readability, but they do not enforce architecture or authorization boundaries.

9. Be Careful with Barrel Files

A barrel file re-exports modules from one location.

For example:

ts
// components/ui/index.ts

export { Button } from "./Button";
export { Input } from "./Input";
export { Dialog } from "./Dialog";

This allows imports such as:

ts
import { Button, Input } from "@/components/ui";

Barrel files can provide convenient public interfaces.

However, a large barrel that re-exports many unrelated modules can also complicate dependency analysis and, depending on the tooling and package design, affect build or development performance.

Should you remove every barrel file?

No.

Modern tooling can optimize many import patterns.

The important thing is to avoid assuming a barrel is always free or always expensive.

Keep exports intentional.

If performance or module dependency problems appear, inspect your actual bundle and import graph.

For cross-feature imports, direct imports can also make module boundaries easier to understand.

10. Where Should Tests Go?

Tests should be easy to locate alongside the code they verify.

For small feature modules, colocating tests can work well:

text
features/
└── inventory/
    ├── queries.ts
    ├── actions.ts
    └── actions.test.ts

For integration or end-to-end tests, a dedicated project-level directory may be more practical:

text
tests/
├── integration/
│   └── inventory.test.ts
└── e2e/
    └── login.spec.ts

Both approaches are reasonable.

Choose a convention that your team understands and follows consistently.

The important distinction is between isolated unit tests, integration tests involving real dependencies, and browser-based end-to-end tests.

A mocked database response does not prove that real Row Level Security policies work.

11. Common Next.js Folder Structure Mistakes

Putting every component in one folder

A single flat directory becomes difficult to scan as a project grows.

Introduce shared and feature-specific boundaries when there is a clear need.

Creating too many architectural layers

Folders such as services, repositories, adapters, and use-cases are not inherently bad.

But creating all of them before your application needs them adds complexity without clear benefits.

Use abstractions to solve observed problems.

Mixing browser and server code

Server-only credentials, database operations, and protected environment variables should not be imported into client-side modules.

Keep these boundaries explicit.

Assuming route groups provide security

Folders named (admin) or (private) are organizational conventions.

They do not authenticate users or restrict database access.

Putting every Server Action into one file

One giant action module can become difficult to maintain when unrelated features depend on it.

Group actions by feature when that improves ownership and maintainability.

Creating circular dependencies

Be careful when shared utilities import feature modules and those features import the same shared utilities.

Try to keep dependency direction understandable.

Refactoring folders too frequently

A project structure doesn't need to be redesigned every time a new feature arrives.

Adopt consistent rules and make structural changes when they provide a meaningful benefit.

12. Does a Small Next.js Project Need This Structure?

Usually not.

A small website might need only:

text
src/
├── app/
│   ├── page.tsx
│   ├── layout.tsx
│   └── globals.css
├── components/
└── lib/

That's perfectly reasonable.

As the application grows, you can introduce feature folders, dedicated authentication helpers, and more specialized components.

A project with several business domains and multiple developers may benefit from stronger boundaries much earlier.

There is no universal number of files, pages, or developers at which a particular structure becomes mandatory.

A practical migration approach

If you already have a large, disorganized Next.js project, don't move every file at once.

Instead:

  1. Identify one feature with scattered files.
  2. Create a feature directory for its business logic.
  3. Move the relevant modules carefully.
  4. Update imports and aliases.
  5. Run type checking and application tests.
  6. Repeat only when the new organization proves useful.

Gradual restructuring is easier to review than a large rewrite that changes hundreds of paths simultaneously.

Final Thoughts

A scalable Next.js folder structure should make your application easier to understand, not harder to navigate.

The App Router already provides clear conventions for routes, layouts, loading states, and Route Handlers.

Build on those conventions.

Keep reusable components separate from feature-specific logic. Group related business code together. Establish explicit browser/server boundaries, and put authorization near the data and operations it protects.

Most importantly, don't confuse organization with security.

A clean directory tree can improve maintenance, but it cannot replace authentication, Row Level Security, or server-side permission checks.

The goal isn't to create the most impressive folder tree.

It's to make it easier for the next developer—or your future self—to understand where the code belongs and how the application fits together.

Official Documentation

Keep the conversation useful

Found a different result?

Include your framework version, the error, and the steps to reproduce it. Specific details help improve the article for the next reader.

Send a correction or question

Share this article