#nextjs #navigation #link #router

Day 4 β€” Navigation & Linking: Moving Between Pages

🧭 Day 4 β€” Navigation & Linking: Moving Between Pages

Zero to Hero β€” Hands-on Next.js Tutorial

In a Single Page Application (SPA), we never want to do a β€œhard refresh” of the browser. We want to swap the content instantly. Next.js makes this incredibly fast with the <Link> component.


Never use the HTML <a> tag for internal links. It causes a full page reload (slow!). Instead, import Link from next/link.

import Link from 'next/link';

export default function NavBar() {
  return (
    <nav className="flex gap-4">
      <Link href="/">Home</Link>
      <Link href="/about">About</Link>
      <Link href="/blog/123">Read Post</Link>
    </nav>
  );
}

Why use <Link>?

  1. Client-side Navigation: Instant transitions.
  2. Prefetching: Next.js automatically loads the code for the linked page in the background as soon as the link enters the viewport. By the time you click, it’s already there. ⚑

How do we style the β€œHome” link differently if we are currently on the Home page? We use the usePathname() hook.

Note: Since hooks need the browser, this must be a Client Component ('use client').

'use client'; // Required for hooks!

import Link from 'next/link';
import { usePathname } from 'next/navigation';

export default function NavLinks() {
  const pathname = usePathname();

  return (
    <nav>
      <Link 
        href="/dashboard" 
        className={pathname === '/dashboard' ? 'text-blue-500 font-bold' : 'text-gray-500'}
      >
        Dashboard
      </Link>
    </nav>
  );
}

🟧 3. Programmatic Navigation (useRouter)

Sometimes you need to navigate after an action (e.g., submitting a login form), not just by clicking a link. Use useRouter from next/navigation.

'use client';

import { useRouter } from 'next/navigation';

export default function LoginPage() {
  const router = useRouter();

  const handleLogin = async () => {
    // ... perform login logic ...
    router.push('/dashboard'); // Navigate to dashboard
    // router.replace('/dashboard'); // Replace history (can't go back)
  };

  return <button onClick={handleLogin}>Log In</button>;
}

πŸŸ₯ 4. Server-Side Redirects

If you are on the server (e.g., in a Server Component or Server Action) and want to redirect the user, use the redirect function.

import { redirect } from 'next/navigation';

export default async function ProtectedPage() {
  const session = await getSession();

  if (!session) {
    redirect('/login'); // Throws an error to stop execution and redirect
  }

  return <h1>Welcome back!</h1>;
}

πŸ§ͺ Challenge: Day 4

  1. Create a NavBar component.
  2. Add links to Home (/), About (/about), and Blog (/blog).
  3. Make the current link bold and red using usePathname.
  4. Include this NavBar in your src/app/layout.tsx so it appears on every page.

See you tomorrow for Styling & Fonts! 🎨