Skip to content

Next.js - Pages

Next.js - Creating Pages with the App Router

Section titled “Next.js - Creating Pages with the App Router”

In modern Next.js, we create web pages using the App Router. This system uses folders and special files within the app directory to define routes. Think of it like organizing files on your computer, where each folder represents a part of the URL.

A ‘page’ in Next.js is a React Server Component exported from a page.tsx (or page.js) file. The route is determined by the file’s location within the app directory.

  • app/page.tsx corresponds to the root route (’/’).
  • app/dashboard/settings/page.tsx corresponds to the ‘/dashboard/settings’ route.

Let’s create a basic Next.js project if you haven’t already. Open your terminal and run:

npx create-next-app@latest my-next-app
cd my-next-app

Follow the prompts, ensuring you select TypeScript and the App Router (which is the default).

Now, let’s create a new page. Create a folder named posts inside the app directory. Inside app/posts/, create a file named page.tsx with the following content:

app/posts/page.tsx
export default function PostsPage() {
return (
<main>
<h1>All Posts</h1>
<p>This is where a list of posts would go.</p>
</main>
);
}

To navigate between pages without a full page reload (client-side navigation), we use the Link component from next/link. Let’s add a link from the home page (app/page.tsx) to our new posts page.

Update app/page.tsx:

app/page.tsx
import Link from 'next/link';
export default function HomePage() {
return (
<main>
<h1>Welcome to Next.js!</h1>
<p>Explore our content:</p>
<Link href="/posts">Go to Posts</Link>
</main>
);
}

Now, let’s add a link back to the home page from the posts page. Update app/posts/page.tsx:

app/posts/page.tsx
import Link from 'next/link';
export default function PostsPage() {
return (
<main>
<h1>All Posts</h1>
<p>This is where a list of posts would go.</p>
<Link href="/">Back to Home</Link>
</main>
);
}

Run the following command in your project’s root directory:

npm run dev

You’ll see output similar to this:

> my-next-app@0.1.0 dev
> next dev
▲ Next.js 14.x.x
- Local: http://localhost:3000
✓ Ready in x.xms
○ Compiling / ...
✓ Compiled / in x.xms

Open http://localhost:3000 in your browser. You should see the home page with the ‘Welcome to Next.js!’ heading and a ‘Go to Posts’ link.

Click the ‘Go to Posts’ link. The URL should change to /posts, and you’ll see the ‘All Posts’ page content, including the ‘Back to Home’ link. Notice the navigation is fast because it’s handled on the client-side by Next.js.