Guide

Getting Started with Next.js 14: A Complete Guide

Learn how to build modern web applications with Next.js 14, including App Router, Server Components, and best practices for performance and SEO.

Tech Dev Mantra
October 20, 2024
4 min read
nextjsreacttypescriptweb-development
Getting Started with Next.js 14: A Complete Guide

Getting Started with Next.js 14: A Complete Guide

Next.js 14 represents a significant leap forward in React framework capabilities, introducing powerful features that make building modern web applications easier and more performant than ever before.

Why Next.js 14?

Next.js has become the go-to framework for React developers who want to build production-ready applications with excellent performance and developer experience. Version 14 brings several improvements:

  • Turbopack: Faster local development with Rust-powered bundling
  • Server Actions: Built-in mutations without API routes
  • Partial Prerendering: Combine static and dynamic rendering
  • Enhanced Image Optimization: Better performance out of the box

Installation

Getting started with Next.js 14 is straightforward. Create a new project using:

npx create-next-app@latest my-app
cd my-app
npm run dev

During installation, you'll be prompted to choose:

  • TypeScript (recommended)
  • ESLint
  • Tailwind CSS
  • App Router (use this!)
  • Turbopack for dev server

Project Structure

Next.js 14 with App Router uses a file-system-based routing structure:

app/
├── layout.tsx       # Root layout
├── page.tsx         # Home page
├── about/
│   └── page.tsx    # /about route
└── blog/
    ├── page.tsx    # /blog route
    └── [slug]/
        └── page.tsx # /blog/[slug] dynamic route

Server Components by Default

One of the most powerful features is that all components are Server Components by default:

// This runs on the server!
async function BlogPost({ params }: { params: { slug: string } }) {
  const post = await fetchPost(params.slug);
  
  return (
    <article>
      <h1>{post.title}</h1>
      <div>{post.content}</div>
    </article>
  );
}

export default BlogPost;

When to Use Client Components

Add 'use client' directive when you need:

  • Event handlers (onClick, onChange, etc.)
  • React hooks (useState, useEffect, etc.)
  • Browser-only APIs
  • Interactive features
'use client';

import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);
  
  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

Data Fetching

Next.js 14 makes data fetching incredibly simple:

// Fetch data directly in your component
async function getData() {
  const res = await fetch('https://api.example.com/data', {
    next: { revalidate: 3600 } // Revalidate every hour
  });
  
  return res.json();
}

export default async function Page() {
  const data = await getData();
  
  return <div>{/* Use your data */}</div>;
}

Caching Strategies

  • Static: Default behavior, data fetched at build time
  • Dynamic: Set cache: 'no-store' for real-time data
  • Revalidated: Use revalidate option for periodic updates

Routing and Navigation

Dynamic Routes

Create dynamic routes using square brackets:

// app/blog/[slug]/page.tsx
export default function BlogPost({ 
  params 
}: { 
  params: { slug: string } 
}) {
  return <h1>Post: {params.slug}</h1>;
}

Link Component

Use the Link component for client-side navigation:

import Link from 'next/link';

export default function Nav() {
  return (
    <nav>
      <Link href="/">Home</Link>
      <Link href="/blog">Blog</Link>
      <Link href="/about">About</Link>
    </nav>
  );
}

Metadata and SEO

Next.js 14 provides excellent SEO support:

import { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'My Page Title',
  description: 'Page description for SEO',
  openGraph: {
    title: 'My Page Title',
    description: 'Page description for SEO',
    images: ['/og-image.jpg'],
  },
};

export default function Page() {
  return <div>Content</div>;
}

Dynamic Metadata

Generate metadata based on route parameters:

export async function generateMetadata({ 
  params 
}: { 
  params: { slug: string } 
}): Promise<Metadata> {
  const post = await fetchPost(params.slug);
  
  return {
    title: post.title,
    description: post.excerpt,
  };
}

Image Optimization

The Image component automatically optimizes images:

import Image from 'next/image';

export default function Avatar() {
  return (
    <Image
      src="/avatar.jpg"
      alt="User avatar"
      width={200}
      height={200}
      priority // Load image with high priority
    />
  );
}

Best Practices

  1. Use Server Components by default - Only add 'use client' when necessary
  2. Leverage Streaming - Show partial content while data loads
  3. Optimize Images - Always use the Image component
  4. Implement Proper SEO - Use metadata API for all pages
  5. Use TypeScript - Catch errors early and improve DX
  6. Code Splitting - Import heavy components dynamically

Performance Tips

Loading States

// app/blog/loading.tsx
export default function Loading() {
  return <div>Loading...</div>;
}

Error Handling

// app/blog/error.tsx
'use client';

export default function Error({
  error,
  reset,
}: {
  error: Error;
  reset: () => void;
}) {
  return (
    <div>
      <h2>Something went wrong!</h2>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

Conclusion

Next.js 14 is a powerful framework that combines the best of static and dynamic rendering, with excellent developer experience and outstanding performance. Whether you're building a simple blog or a complex web application, Next.js 14 provides all the tools you need.

Start building with Next.js 14 today and experience the future of React development!

Resources