| | |

Nuxt 02 ๐Ÿ’š Project Structure (app/, server/, shared/) โ€” Navigating Nuxt 4 isolated directories, auto-imports, and split TypeScript contexts

โฑ๏ธ Estimated read: 11 min | |

Nuxt 4 introduces a significant architectural evolution designed to solve the complexity of large-scale, full-stack applications. In previous versions, the root directory was often cluttered with a mix of frontend folders (like pages and components) and backend folders (like server). This made it difficult to manage TypeScript configurations and occasionally led to “leaked” logic, where frontend code accidentally tried to import server-only utilities.

The new structure in Nuxt 4 formalizes the separation of concerns by introducing dedicated, isolated directories. The frontend logic now resides primarily in the app/ directory, while backend logic remains in the server/ directory. To facilitate communication between these two distinct worlds without duplicating code, Nuxt 4 introduces the shared/ directory. This creates a clean “Split Context” environment where each part of your application knows exactly where it belongs and what resources it can access.

This chapter walks through the purpose and mechanics of these three core directories. We will explore how auto-imports behave across these boundaries and why the split TypeScript context is a game-changer for developer experience. By organizing your project this way, you ensure that your code is not only more readable but also more robust, as Nuxt can now enforce stricter build-time checks to prevent cross-environment errors.

Finally, we will look at how Nuxt 4 maintains compatibility while encouraging this new standard. Whether you are migrating an existing Nuxt 3 project or starting a fresh Nuxt 4 application, understanding this structural layout is the key to mastering modern web development with Vue and Nitro.

Key point: Nuxt 4 moves the frontend application into the app/ directory and introduces a shared/ directory to create physical isolation between the browser and server environments, enabling distinct TypeScript contexts and preventing cross-environment logic leaks.


Why exists

The “Root Pollution” problem

In Nuxt 3, the root of the project was the “junk drawer” of the application. Configuration files (like nuxt.config.ts and package.json) lived side-by-side with your UI logic (pages, components). As projects grew, finding specific frontend files became difficult. Nuxt 4 solves this by moving all UI-related code into a dedicated app/ folder, keeping the root clean and focused on project-level configuration.

The “TypeScript Leak” problem

Browser-side code and server-side code have different capabilities. For example, the browser has access to window, while the server has access to the file system (fs). In a unified directory structure, TypeScript often struggled to differentiate between these two, leading to “false positive” autocomplete suggestions. Isolated directories allow Nuxt to generate specific TypeScript contexts for each folder, ensuring you only see valid APIs for the environment you are currently coding in.

The “Shared Logic” ambiguity

Developers frequently need to share TypeScript interfaces, validation schemas (like Zod), or utility functions between the frontend and the backend. Without a dedicated shared/ folder, developers often created a random utils/ folder in the root, which lacked clear rules about which environment it belonged to. The shared/ directory provides a formal, sanctioned home for code that must run everywhere.

The “Build Isolation” advantage

By physically separating the app/ and server/ directories, the Nuxt build engine (Vite and Nitro) can process files more efficiently. It no longer has to guess which files are part of the client bundle and which are part of the server bundle based on file extensions or naming conventions alone. This isolation leads to faster build times and more reliable tree-shaking.

The “Layer Scaling” problem

Nuxt Layers are a powerful feature for sharing code between projects. However, managing layers that mixed frontend and backend code was often confusing. The isolated directory structure makes layers more predictable; you can easily tell what a layer is contributing to the “App” layer versus what it is contributing to the “Server” layer.


a. The app/ Directory: The Frontend Home

In Nuxt 4, the app/ directory is the new standard root for your Vue application. This is where your UI-specific logic lives. If you have been using Nuxt 3, you can think of the app/ folder as a wrapper for everything you used to put in the root. By default, Nuxt looks for your pages/, components/, layouts/, composables/, middleware/, and plugins/ inside this directory.

app/
โ”œโ”€โ”€ components/
โ”‚   โ””โ”€โ”€ AppHeader.vue
โ”œโ”€โ”€ composables/
โ”‚   โ””โ”€โ”€ useAuth.ts
โ”œโ”€โ”€ layouts/
โ”‚   โ””โ”€โ”€ default.vue
โ”œโ”€โ”€ pages/
โ”‚   โ””โ”€โ”€ index.vue
โ””โ”€โ”€ app.vue

The app.vue file, which is the entry point of your application, also moves here. This structure ensures that your frontend is a self-contained unit. Because this directory is isolated, the auto-imports generated for this folder include Vue-specific APIs (like ref and computed) and browser-specific global types.


b. The server/ and shared/ Directories

The server/ directory remains the home for your Nitro engine logic. It handles your API routes, server-side middleware, and server-only utilities. Code inside this folder never reaches the browser. It is strictly for Node.js (or other serverless) environments.

server/
โ”œโ”€โ”€ api/
โ”‚   โ””โ”€โ”€ users.ts
โ”œโ”€โ”€ middleware/
โ”‚   โ””โ”€โ”€ auth.ts
โ””โ”€โ”€ utils/
    โ””โ”€โ”€ db.ts

The shared/ directory is the bridge. It is specifically designed for code that needs to be accessed by both the app/ and the server/. Common use cases include TypeScript types, constants (like error codes or status strings), and validation logic.

shared/
โ”œโ”€โ”€ utils/
โ”‚   โ””โ”€โ”€ formatter.ts
โ””โ”€โ”€ types/
    โ””โ”€โ”€ index.ts

Auto-imports from shared/ are available in both the app/ and server/ contexts. This eliminates the need for manual relative imports (like ../../shared/types) and ensures that your data models are consistent across the entire full-stack application.


c. Split TypeScript Contexts

One of the most powerful features of the Nuxt 4 structure is the Split TypeScript Context. In a traditional Nuxt 3 setup, there was one primary tsconfig.json. In Nuxt 4, Nuxt generates separate “internal” TypeScript configurations for different parts of the app.

When you are editing a file in app/, the IDE knows you are in a “Browser” context. It will allow document.querySelector but will flag process.env as potentially dangerous or undefined. Conversely, when you are in server/, the IDE knows you are in a “Server” context. It will allow fs.readFile but will red-line any attempt to use localStorage.

This is achieved through the .nuxt directory, where Nuxt creates multiple specific tsconfig files:

  1. .nuxt/tsconfig.app.json
  2. .nuxt/tsconfig.server.json

By using the shared/ directory, you ensure that shared code is compiled with a set of rules compatible with both environments (usually standard ESModules without environment-specific globals), making your shared logic truly portable and type-safe.


Complete Example Session

// ============================================
// PART 1: THE SHARED DATA MODEL
// ============================================
// File: shared/types/user.ts
export interface User {
  id: number;
  username: string;
  role: 'admin' | 'user';
}

// ============================================
// PART 2: THE SERVER API (Backend)
// ============================================
// File: server/api/me.get.ts
// Context: Server (Access to headers, cookies, DB)
export default defineEventHandler((event) => {
  // We can use the shared type here!
  const user: User = { id: 1, username: 'nuxt_dev', role: 'admin' };
  return user;
});

// ============================================
// PART 3: THE FRONTEND UI (Frontend)
// ============================================
// File: app/pages/profile.vue
// Context: Browser (Vue, Ref, useFetch)
<script setup lang="ts">
// 'User' is auto-imported from shared/
const { data: user } = await useFetch<User>('/api/me');
</script>

<template>
  <div v-if="user">
    <h1>Welcome, {{ user.username }}</h1>
    <p>Role: {{ user.role }}</p>
  </div>
</template>

// ============================================
// PART 4: PROJECT-LEVEL CONFIG
// ============================================
// File: nuxt.config.ts
// Lives at the root, managing the whole orchestration
export default defineNuxtConfig({
  future: {
    compatibilityVersion: 4, // Enables the app/ structure
  },
});

This sequence demonstrates how a single type definition in shared/ flows seamlessly into a Nitro API route in server/ and then into a Vue component in app/, with full type safety and auto-imports across all boundaries.


Quick Reference

Isolated Directory Purposes

DirectoryTarget EnvironmentKey Contents
app/Browser (Client)Pages, Components, Composables, app.vue
server/Nitro (Server)API routes, Server Middleware, Server Utils
shared/Isomorphic (Both)Types, Constants, Validation Schemas

Standard Folder Mapping (Nuxt 4)

Old Nuxt 3 PathNew Nuxt 4 Path
components/app/components/
pages/app/pages/
composables/app/composables/
server/api/server/api/ (Stays the same)
assets/app/assets/

Auto-Import Visibility

Source FolderVisible in app/?Visible in server/?
app/composablesโœ… YesโŒ No
server/utilsโŒ Noโœ… Yes
shared/utilsโœ… Yesโœ… Yes

Best Practices

โœ… Do This:

// Put Zod schemas for form validation in shared/
export const LoginSchema = z.object({ ... });                 // โœ…

// Keep app.vue inside the app/ folder
// Path: app/app.vue                                          // โœ…

// Use shared/ for TypeScript interfaces used in APIs
// Path: shared/types/api.ts                                   // โœ…

// Keep database connection logic strictly in server/utils
// Path: server/utils/db.ts                                   // โœ…

โŒ Don’t Do This:

// Don't import browser-only logic in shared/
import { useLocalStorage } from '@vueuse/core';               // โŒ

// Don't put UI components in the root pages/ folder
// Path: pages/index.vue (Move to app/pages/index.vue)         // โŒ

// Don't use Node 'fs' module in shared/ logic
import fs from 'node:fs';                                     // โŒ

// Don't try to access 'window' in a server/ middleware
if (window.innerWidth) { ... }                                // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Missing Auto-importsYou put a file in src/ instead of app/.Ensure future.compatibilityVersion: 4 is set.
Type Error in SharedShared code uses a browser or server global.Use process.client or process.server checks.
Root pages ignoredNuxt 4 expects pages to be in app/pages.Move the pages folder inside the app folder.
IDE shows errorsThe IDE is using the root tsconfig for all files.Restart the TS Server in your IDE.
Leaked Server SecretImporting a server utility into the app/ folder.Move non-secret logic to shared/ or keep it in server/.

Real-World Examples

1. Defining a shared enum

// shared/constants.ts
export enum UserRole { ADMIN = 'admin', USER = 'user' }

2. Shared string formatter

// shared/utils/format.ts
export const toCurrency = (val: number) => `$${val.toFixed(2)}`;

3. Frontend-only plugin

// app/plugins/analytics.client.ts
export default defineNuxtPlugin(() => { /* analytics logic */ });

4. Backend-only database helper

// server/utils/prisma.ts
import { PrismaClient } from '@prisma/client';
export const prisma = new PrismaClient();

5. Shared validation with Zod

// shared/utils/validation.ts
import { z } from 'zod';
export const UserSchema = z.object({ name: z.string() });

6. Global frontend styles

// app/assets/css/main.css
body { background: #f0f0f0; }

7. Server-side session middleware

// server/middleware/session.ts
export default defineEventHandler((event) => { /* session logic */ });

8. Layout file in isolated app

<!-- app/layouts/admin.vue -->
<template><nav>Admin Sidebar</nav><slot /></template>

9. Shared error constants

// shared/errors.ts
export const ERR_NOT_FOUND = { code: 404, msg: 'Not Found' };

10. Frontend-only composable

// app/composables/useTheme.ts
export const useTheme = () => useState('theme', () => 'light');

Visual

The Nuxt 4 Directory Concept

    ROOT (Configs: nuxt.config.ts, package.json)
    โ”‚
    โ”œโ”€โ”€ app/ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ [ THE CLIENT WORLD ]
    โ”‚   โ”œโ”€โ”€ pages/               - Vue Components
    โ”‚   โ”œโ”€โ”€ components/          - Browser APIs
    โ”‚   โ””โ”€โ”€ app.vue              - Window / Document
    โ”‚
    โ”œโ”€โ”€ server/ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ [ THE SERVER WORLD ]
    โ”‚   โ”œโ”€โ”€ api/                 - Nitro Logic
    โ”‚   โ””โ”€โ”€ utils/               - Node.js APIs (fs, path)
    โ”‚                            - Database Secrets
    โ”‚
    โ””โ”€โ”€ shared/ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ [ THE BRIDGE ]
        โ”œโ”€โ”€ types/               - TS Interfaces
        โ””โ”€โ”€ utils/               - Safe logic for both

TypeScript Context Separation

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚     TS CONTEXT: APP     โ”‚         โ”‚   TS CONTEXT: SERVER    โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค         โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ โœ… ref, computed        โ”‚         โ”‚ โŒ ref, computed        โ”‚
โ”‚ โœ… window, document     โ”‚         โ”‚ โŒ window, document     โ”‚
โ”‚ โŒ fs, node:path        โ”‚         โ”‚ โœ… fs, node:path        โ”‚
โ”‚ โœ… shared/types         โ”‚         โ”‚ โœ… shared/types         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Auto-Import Flow

   [ shared/utils ] โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                           โ”‚ (Visible in both)
        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
        โ–ผ                                     โ–ผ
   [ app/pages ]                         [ server/api ]
        โ–ฒ                                     โ–ฒ
        โ”‚ (Visible only in app)               โ”‚ (Visible only in server)
   [ app/composables ]                   [ server/utils ]

Summary

ItemValue
Frontend Rootapp/
Backend Rootserver/
Isomorphic Rootshared/
Config Keyfuture.compatibilityVersion: 4
TS BenefitSplit Context (No leaked globals)
PerformanceBetter Tree-shaking & Build Isolation
Primary GoalScale large full-stack Vue apps

Key takeaways:

  • Nuxt 4 formalizes isolation. By moving the Vue app into app/, the root remains dedicated to configuration, reducing clutter.
  • The shared/ directory is essential. It provides a safe harbor for types and logic that must be identical on both the client and server.
  • TypeScript is now environment-aware. Separate contexts prevent you from using browser-only APIs on the server and vice-versa, catching bugs during development.
  • Auto-imports are scoped. Logic in app/ is only auto-imported into the frontend, and logic in server/ is only auto-imported into the backend, while shared/ logic is available everywhere.
  • The structure is future-proof. This layout is designed to handle massive applications with dozens of pages and complex server logic without becoming unmanageable.
  • Migration is optional but recommended. You can still run Nuxt 4 with a Nuxt 3 structure, but adopting the new layout unlocks the full benefits of isolated contexts.

Remember: Use app/ for anything the user sees, server/ for anything that touches your data or secrets, and shared/ for the “glue” that holds your types and validation logic together.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!