Next.js Lesson 5 – Pages and Routing | Dataplexa
LESSON 5

Pages and Routing

Transform your NewsWave website from static React components into a multi-page application using Next.js's file-based routing system.

Next.js revolutionizes how you create pages compared to traditional React applications. Instead of setting up React Router and writing configuration files, Next.js uses your file system to automatically create routes. Every file you place in specific directories becomes a page that users can visit. Think of it like organizing a filing cabinet. In regular React, you need to write a detailed map explaining which drawer contains which files. With Next.js, the file structure IS the map. Create a file called about.js and visitors can instantly access yoursite.com/about. No configuration needed. This approach eliminates the complexity of route definitions while making your project structure incredibly intuitive. When you see the folder structure, you immediately understand the site's navigation. The NewsWave team chose Next.js specifically because this file-based routing makes it easy to add new article categories and pages without touching configuration files.

Understanding Next.js Routing

Traditional React applications require you to install React Router, wrap your app in a Router component, and define routes manually. You write JSX that maps URL paths to specific components. Every time you add a new page, you update the routing configuration. Next.js flips this approach completely. The router is built into the framework, and your file structure automatically generates routes. Place a React component in the pages directory (in Pages Router) or create page.js files in the app directory (in App Router), and that component becomes accessible at the corresponding URL path. The magic happens during the build process. Next.js scans your file structure and automatically generates the routing table. When a user navigates to a page, Next.js knows exactly which component to render based on the file path. This eliminates routing bugs and reduces the amount of boilerplate code you need to write.
NewsWave File Structure
📁 newswave/
📁 app/
📄 page.js → /
📄 layout.js → Root layout
📁 about/
📄 page.js → /about
📁 articles/
📄 page.js → /articles
📁 category/
📄 page.js → /category

Creating Your First Pages

Your NewsWave homepage needs to display featured articles and breaking news. Since you already have the basic structure set up, you need to create the main page component. The homepage lives in the root of your app directory as page.js. Every page in Next.js is just a React component that gets exported as the default export. The component receives props like params and searchParams that contain URL information, but for static pages, you often don't need these. The key difference from regular React components is that Next.js page components can be async functions. This allows you to fetch data directly in the component before rendering, which is impossible in client-side React. For now, you'll create a simple page that displays mock news data.
// app/page.js - NewsWave homepage
export default function HomePage() {
  return (
    <div>
      <h1>NewsWave</h1>
      <p>Your trusted source for breaking news and analysis</p>
      
      <section>
        <h2>Featured Articles</h2>
        <p>Latest stories from around the world</p>
      </section>
    </div>
  )
}
localhost:3000 — NewsWave

What just happened?

You created a Next.js page component that automatically becomes available at the root URL. The default export makes this component the page that renders when users visit your site. Next.js handles all the routing logic behind the scenes.

Now you need an about page for NewsWave. This demonstrates how simple it is to add new pages in Next.js. Create a new folder called about and place a page.js file inside it. The folder name becomes part of the URL path.
// app/about/page.js - NewsWave about page  
export default function AboutPage() {
  return (
    <div>
      <h1>About NewsWave</h1>
      <p>Founded in 2024, NewsWave delivers accurate, unbiased news coverage</p>
      
      <h2>Our Mission</h2>
      <p>To provide trustworthy journalism in the digital age</p>
      
      <h2>Contact Us</h2>
      <p>Email: contact@newswave.com</p>
    </div>
  )
}
localhost:3000/about — NewsWave

Route Organization Patterns

As NewsWave grows, you need a logical way to organize pages. Next.js provides several patterns for structuring routes that scale from simple websites to complex applications. The key is understanding how folder names translate to URL paths and when to use different organizational approaches. Route groups allow you to organize files without affecting the URL structure. Wrap folder names in parentheses like (marketing) or (dashboard) to group related pages together without adding those names to the URL path. This helps keep your file structure clean while maintaining logical groupings. Nested routes work exactly as you'd expect. Create folders inside folders, and the URL path follows the same structure. A file at app/category/tech/page.js becomes accessible at /category/tech. Each folder can have its own layout file that wraps all child pages, creating consistent navigation and styling.
Advanced NewsWave Structure
📁 app/
📄 page.js → /
📄 layout.js → Root layout
📁 (marketing)/
📁 about/
📄 page.js → /about
📁 contact/
📄 page.js → /contact
📁 category/
📄 layout.js → Category layout
📁 tech/
📄 page.js → /category/tech
📁 world/
📄 page.js → /category/world

Special Files in Next.js Routing

Next.js recognizes several special file names that serve specific purposes in your routing system. These files control different aspects of how pages render and behave, giving you fine-grained control over the user experience without writing complex configuration. The layout.js file wraps all pages in the same folder and subfolders. Think of it as a template that provides consistent navigation, headers, and footers across multiple pages. Unlike regular components, layouts preserve state when users navigate between pages, making them perfect for persistent UI elements. The loading.js file creates a loading UI that shows while pages are being fetched or rendered. This is especially useful for pages that fetch data from APIs, as users see immediate feedback instead of a blank screen. The error.js file handles errors gracefully by providing a custom error boundary that catches JavaScript errors and displays user-friendly messages.
// app/category/layout.js - Shared layout for all category pages
export default function CategoryLayout({ children }) {
  return (
    <div>
      <nav>
        <h2>Browse Categories</h2>
        <ul>
          <li>Tech</li>
          <li>World</li>
          <li>Business</li>
        </ul>
      </nav>
      <main>{children}</main>
    </div>
  )
}
localhost:3000/category/tech — NewsWave

What just happened?

You created a layout component that wraps all category pages with consistent navigation. The children prop contains the actual page content, while the layout provides the surrounding structure. This layout applies to all pages in the category folder automatically.

Navigation Between Pages

Creating pages is only half the story. Users need a way to navigate between them. While you could use regular HTML anchor tags, Next.js provides a specialized Link component that enables client-side navigation. This means page transitions happen instantly without full page reloads, creating a much smoother user experience. The Link component preloads pages in the background when they appear in the viewport. This prefetching behavior means that by the time a user clicks a link, the destination page is often already loaded. The result is navigation that feels instant, similar to single-page applications but with the SEO benefits of multiple pages. Traditional anchor tags cause the browser to request a completely new page from the server, reload all JavaScript bundles, and reinitialize the entire React application. The Link component maintains the application state, preserves scroll positions where appropriate, and only updates the parts of the page that actually change.
// app/components/Navigation.js - NewsWave navigation component
import Link from 'next/link'

export default function Navigation() {
  return (
    <nav>
      <Link href="/">Home</Link>
      <Link href="/about">About</Link>
      <Link href="/category/tech">Tech</Link>
      <Link href="/category/world">World</Link>
    </nav>
  )
}
localhost:3000 — NewsWave Navigation

Programmatic Navigation

Sometimes you need to navigate users programmatically rather than through click events. Form submissions, authentication flows, and conditional redirects all require navigation that happens in response to application logic rather than user clicks. Next.js provides the useRouter hook for these scenarios. The router object gives you methods to push new routes onto the history stack, replace the current route, or go back to previous pages. The push method adds a new entry to the browser history, while replace substitutes the current page without affecting the back button behavior. You can also access URL parameters and query strings through the router object. This becomes essential when building search functionality for NewsWave, where you need to read search terms from the URL and potentially update them based on user actions.
// app/components/SearchForm.js - Navigate after search
'use client'
import { useRouter } from 'next/navigation'
import { useState } from 'react'

export default function SearchForm() {
  const router = useRouter()
  const [query, setQuery] = useState('')
  
  const handleSearch = (e) => {
    e.preventDefault()
    if (query.trim()) {
      router.push(`/search?q=${encodeURIComponent(query)}`)
    }
  }
  
  return (
    <form onSubmit={handleSearch}>
      <input 
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search news..."
      />
      <button type="submit">Search</button>
    </form>
  )
}
localhost:3000 — NewsWave Search

What just happened?

You created a search form that uses programmatic navigation to redirect users to search results. The 'use client' directive makes this a client component since it uses browser APIs and state. The router.push method navigates to the search page with the query as a URL parameter.

Building the Complete NewsWave Navigation

Now you can combine all these routing concepts to build NewsWave's complete navigation system. The site needs a persistent header with navigation links, breadcrumbs for category pages, and a search form that works across the entire application. The root layout is the perfect place to put global navigation since it wraps every page in your application. This ensures consistent navigation regardless of which page users visit first or how they navigate through the site. The layout also handles the overall page structure that every page shares.
// app/layout.js - Root layout with navigation
import Link from 'next/link'

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <header>
          <div>
            <Link href="/">NewsWave</Link>
            <nav>
              <Link href="/category/tech">Tech</Link>
              <Link href="/category/world">World</Link>
              <Link href="/category/business">Business</Link>
              <Link href="/about">About</Link>
            </nav>
          </div>
        </header>
        <main>{children}</main>
      </body>
    </html>
  )
}
localhost:3000 — NewsWave

Common Routing Mistakes

Avoid these routing pitfalls: Don't mix regular anchor tags with Link components for internal navigation. Don't forget the 'use client' directive when using useRouter. Don't create page.js files in route groups - they won't work as expected.

Quiz

1. NewsWave needs a contact page accessible at /contact. Which file path would create this route in the App Router?


2. What is the primary purpose of a layout.js file in Next.js App Router?


3. NewsWave needs to redirect users programmatically after they submit a newsletter signup form. Which Next.js feature should you use?


Up Next: Link and Navigation

Master Next.js Link components, active link styling, prefetching behavior, and advanced navigation patterns that make NewsWave feel lightning fast.