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
- 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 yourpagesdirectory toapp. - Understand the
appdirectory structure. The App Router uses theappfolder at the project root. Every folder insideappcorresponds to a URL segment. For example,app/about/page.tsxbecomes/about. The key files arepage.tsx(the page component),layout.tsx(shared layout for that segment),loading.tsx,error.tsx, andnot-found.tsx. - Create the root layout. The file
app/layout.tsxdefines the HTML shell for the entire app. It must include<html>and<body>tags and achildrenprop. This layout persists across all routes. Example:export default function RootLayout({ children }) { return ( <html lang="en"> <body>{children}</body> </html> ); } - Add a home page. Create
app/page.tsxwith a default exported React component. This renders at the root path/. You can put your homepage content here. - Build nested routes. To create a route like
/dashboard/settings, create a folder structure:app/dashboard/settings/page.tsx. Each folder can have its ownlayout.tsxthat wraps only that segment’s pages. For example,app/dashboard/layout.tsxcould include a sidebar that appears on all dashboard pages. - 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 accessparams.idto fetch data. - Add loading and error states. Create
loading.tsxin any route folder to show a fallback UI while the page’s data is being fetched (it wraps the page in a Suspense boundary). Createerror.tsxto catch errors in that segment; it must be a client component (add'use client'at the top) and receiveserrorandresetprops. - Set up API routes. In the App Router, API routes are defined using route handlers. Create a file like
app/api/hello/route.tsthat exports async functions namedGET,POST, etc. For example:export async function GET() { return Response.json({ message: 'Hello' }); } - Organize components and utilities. Keep shared components in a
componentsfolder at the project root (or insideappif they’re route-specific). Use aliborutilsfolder for helper functions, and apublicfolder for static assets. This separation keeps theappfolder focused on routing. - Test your structure. Run
npm run devand 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.tsxis required for a route to be accessible. A folder without apage.tsxwill 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. Usingindex.tsxorhome.tsxwill 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
Linkfor external URLs. The Next.jsLinkcomponent 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.tsxstill maps to/about. This helps group related routes without adding a URL segment. - Leverage
loading.tsxfor a smoother UX. Even if you don’t fetch data, a loading state prevents layout shift and gives visual feedback. - Use
generateStaticParamsin 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.tsxand 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.cssand 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.,
POSTfor 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
- How to Factory Reset iPad If You Forgot Password
- Ubuntu in Windows Store: Which Editions Work?
- Secure Guest Account on Windows 11: Step-by-Step
- Stop Outlook From Changing Hyperlink Font
- Hiberfil.sys: What It Is & How to Delete It
- How to Make a Mask on Snapchat: Step-by-Step