Nuxt 02 ๐ Project Structure (app/, server/, shared/) โ Navigating Nuxt 4 isolated directories, auto-imports, and split TypeScript contexts
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:
.nuxt/tsconfig.app.json.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
| Directory | Target Environment | Key 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 Path | New 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 Folder | Visible 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Missing Auto-imports | You put a file in src/ instead of app/. | Ensure future.compatibilityVersion: 4 is set. |
| Type Error in Shared | Shared code uses a browser or server global. | Use process.client or process.server checks. |
| Root pages ignored | Nuxt 4 expects pages to be in app/pages. | Move the pages folder inside the app folder. |
| IDE shows errors | The IDE is using the root tsconfig for all files. | Restart the TS Server in your IDE. |
| Leaked Server Secret | Importing 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
| Item | Value |
|---|---|
| Frontend Root | app/ |
| Backend Root | server/ |
| Isomorphic Root | shared/ |
| Config Key | future.compatibilityVersion: 4 |
| TS Benefit | Split Context (No leaked globals) |
| Performance | Better Tree-shaking & Build Isolation |
| Primary Goal | Scale 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 inserver/is only auto-imported into the backend, whileshared/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.
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!