0
0
NextJSframework~5 mins

App directory (App Router) in NextJS

Choose your learning style9 modes available
Introduction

The App directory in Next.js helps organize your app's pages and components in a simple folder structure. It makes routing automatic and easy to manage.

When you want to create a new page in your Next.js app quickly.
When you want to organize your app with nested folders for different sections.
When you want to use server components and layouts easily.
When you want automatic routing without manual route setup.
When you want to add loading states or error handling per route.
Syntax
NextJS
app/
  page.js
  layout.js
  dashboard/
    page.js
    settings/
      page.js

app/ is the main folder for your app's routes.

Each folder inside app/ represents a route segment.

Examples
The page.js file inside app/ is the homepage.
NextJS
app/page.js
// This file creates the homepage at '/' route
A folder inside app/ with a page.js creates a nested route.
NextJS
app/dashboard/page.js
// This file creates the '/dashboard' page
The layout.js file defines a shared layout for all pages inside app/.
NextJS
app/layout.js
// This file wraps all pages with shared layout like header/footer
Sample Program

This example shows a root layout wrapping all pages with a header and footer. The homepage and dashboard pages show different content based on the route.

NextJS
/* app/layout.js */
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <header>
          <h1>My Next.js App</h1>
        </header>
        <main>{children}</main>
        <footer>
          <p>Ā© 2024 My App</p>
        </footer>
      </body>
    </html>
  )
}

/* app/page.js */
export default function HomePage() {
  return <h2>Welcome to the homepage!</h2>
}

/* app/dashboard/page.js */
export default function DashboardPage() {
  return <h2>This is the dashboard.</h2>
}
OutputSuccess
Important Notes

Each page.js file must export a React component as default.

Layouts wrap pages and can be nested for different route segments.

Use the app/ directory for new Next.js projects to get the latest routing features.

Summary

The app/ directory organizes routes by folders and files.

Each folder with a page.js file creates a route.

Layouts in layout.js wrap pages for shared UI.