sodcalculator

10 Tech How-To

Next.js App Router Structure: Step-by-Step

Guide 10-56180 · Updated · Step by step

This guide walks through structuring a Next.js application using the modern App Router, which organizes routes, layouts, and components in a clear, file-based hierarchy. You’ll learn the essential folder and file conventions, how to create nested routes, and how to handle dynamic segments, loading states, and error boundaries. By the end, you’ll have a scalable foundation for building pages, API routes, and shared UI in Next.js 13+ (App Router).

What You’ll Need

  • Node.js 18.17.0 or later installed on your machine
  • Basic familiarity with React and JavaScript/TypeScript
  • A code editor (VS Code recommended)
  • Terminal access to run commands

Step-by-Step

  1. Create a new Next.js project (if you don’t have one) by running npx create-next-app@latest my-app. When prompted, choose Yes for TypeScript (optional but recommended), Yes for ESLint, and select the App Router option. If you’re adding App Router to an existing project, upgrade to Next.js 13+ and move your pages directory to app.
  2. Understand the app directory structure. The App Router uses the app folder at the project root. Every folder inside app corresponds to a URL segment. For example, app/about/page.tsx becomes /about. The key files are page.tsx (the page component), layout.tsx (shared layout for that segment), loading.tsx, error.tsx, and not-found.tsx.
  3. Create the root layout. The file app/layout.tsx defines the HTML shell for the entire app. It must include <html> and <body> tags and a children prop. This layout persists across all routes. Example:
    export default function RootLayout({ children }) {
      return (
        <html lang="en">
          <body>{children}</body>
        </html>
      );
    }
  4. Add a home page. Create app/page.tsx with a default exported React component. This renders at the root path /. You can put your homepage content here.
  5. Build nested routes. To create a route like /dashboard/settings, create a folder structure: app/dashboard/settings/page.tsx. Each folder can have its own layout.tsx that wraps only that segment’s pages. For example, app/dashboard/layout.tsx could include a sidebar that appears on all dashboard pages.
  6. Use dynamic route segments. For routes with variable parts (e.g., a blog post at /posts/1), create a folder with square brackets: app/posts/[id]/page.tsx. The page component receives the dynamic value as a prop: export default function Post({ params }: { params: { id: string } }). You can access params.id to fetch data.
  7. Add loading and error states. Create loading.tsx in any route folder to show a fallback UI while the page’s data is being fetched (it wraps the page in a Suspense boundary). Create error.tsx to catch errors in that segment; it must be a client component (add 'use client' at the top) and receives error and reset props.
  8. Set up API routes. In the App Router, API routes are defined using route handlers. Create a file like app/api/hello/route.ts that exports async functions named GET, POST, etc. For example:
    export async function GET() {
      return Response.json({ message: 'Hello' });
    }
  9. Organize components and utilities. Keep shared components in a components folder at the project root (or inside app if they’re route-specific). Use a lib or utils folder for helper functions, and a public folder for static assets. This separation keeps the app folder focused on routing.
  10. Test your structure. Run npm run dev and navigate to each route to ensure layouts, pages, and dynamic segments work as expected. Check the browser’s network tab for loading states and error handling.

Common Mistakes

  • Forgetting that page.tsx is required for a route to be accessible. A folder without a page.tsx will cause a 404 unless it’s a layout or has a route handler.
  • Putting client components in Server Components by default. In App Router, components are Server Components by default. If you need state, effects, or event handlers, add 'use client' at the top of the file.
  • Misnaming files. The file must be exactly page.tsx, layout.tsx, etc. Using index.tsx or home.tsx will not work.
  • Nesting layouts incorrectly. Layouts do not re-render when navigating between sibling routes, but they do apply to all child routes. Avoid putting route-specific logic in a layout that should be in a page.
  • Using Link for external URLs. The Next.js Link component is for internal navigation. For external links, use a regular <a> tag.

Tips

  • Use route groups to organize folders without affecting the URL. Wrap a folder name in parentheses, e.g., app/(marketing)/about/page.tsx still maps to /about. This helps group related routes without adding a URL segment.
  • Leverage loading.tsx for a smoother UX. Even if you don’t fetch data, a loading state prevents layout shift and gives visual feedback.
  • Use generateStaticParams in dynamic routes to pre-render pages at build time for static generation, improving performance for content that doesn’t change often.
  • Keep the root layout minimal. Only include global providers (like ThemeProvider) and meta tags. Put per-page navigation in nested layouts.
  • Use TypeScript to catch errors early, especially with dynamic params and route handler types.

Troubleshooting

  • Page not found (404): Ensure the file is named page.tsx and is in the correct folder. Check that the folder name matches the desired URL segment.
  • Hydration mismatch errors: This usually happens when server-rendered HTML differs from client-rendered output. Check for browser-specific code (like window) in client components without proper effects, or inconsistent data between server and client.
  • Styles not applying: If using CSS modules, ensure the file is named *.module.css and imported correctly. For global CSS, import it in the root layout.
  • API route returns 405: Make sure you’ve exported the correct HTTP method function (e.g., POST for POST requests).
  • Layout not updating on navigation: If you expect the layout to re-render, remember layouts persist across navigations. Move the dynamic content to a page component instead.

Frequently Asked Questions

What is the difference between the App Router and the Pages Router?

The App Router (introduced in Next.js 13) uses the app directory and supports layouts, server components, and more flexible routing. The Pages Router uses the pages directory with _app.tsx and _document.tsx. App Router is the recommended approach for new projects.

Can I use both App Router and Pages Router in the same project?

Yes, Next.js supports both simultaneously, but it’s not recommended for long-term maintenance. You can gradually migrate pages by moving them into the app directory.

How do I fetch data in a Server Component?

You can use async/await directly in the component. For example, const data = await fetch('https://api.example.com'). The component will be rendered on the server with the data.

How do I create a catch-all route?

Use three dots inside brackets: app/docs/[...slug]/page.tsx. This matches any number of segments, e.g., /docs/a/b/c. The params.slug will be an array of the segments.

How do I redirect from a page?

Use the redirect function from next/navigation in a Server Component or useRouter in a client component. For example: redirect('/login').

What is the purpose of the not-found.tsx file?

It defines the UI for a 404 error within a specific route segment. You can create a custom not-found page for the entire app by placing it in the root app folder.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →