🚀 Getting Started with Next.js 14
Next.js 14 brings significant improvements to the developer experience with the stable App Router, improved performance, and new features.
Why Next.js?
Next.js is the React framework for production. It provides:
- Server-Side Rendering (SSR) - Better SEO and faster initial loads
- Static Site Generation (SSG) - Pre-render pages at build time
- File-based Routing - Intuitive navigation structure
- API Routes - Build APIs within your Next.js app
- Automatic Code Splitting - Load only what’s needed
Quick Start
# Create a new Next.js project
npx create-next-app@latest my-app
# Navigate to project
cd my-app
# Start development server
npm run devApp Router Structure
my-app/
├── app/
│ ├── layout.tsx # Root layout
│ ├── page.tsx # Home page
│ ├── globals.css # Global styles
│ ├── about/
│ │ └── page.tsx # /about route
│ └── blog/
│ ├── page.tsx # /blog
│ └── [slug]/
│ └── page.tsx # /blog/[slug]
├── components/
│ └── Navbar.tsx
├── lib/
│ └── utils.ts
└── public/
└── images/Creating Pages
Basic Page Component
// app/page.tsx
export default function Home() {
return (
<main className="container mx-auto p-4">
<h1 className="text-4xl font-bold">Welcome to My App</h1>
<p className="mt-4 text-gray-600">Built with Next.js 14</p>
</main>
);
}Dynamic Routes
// app/blog/[slug]/page.tsx
interface PageProps {
params: { slug: string };
}
export default function BlogPost({ params }: PageProps) {
return (
<article>
<h1>Post: {params.slug}</h1>
</article>
);
}Server Components
By default, all components in the App Router are Server Components:
// This runs on the server
async function Posts() {
const posts = await fetch("https://api.example.com/posts");
const data = await posts.json();
return (
<ul>
{data.map((post: Post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}Client Components
For interactivity, use the 'use client' directive:
"use client";
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}Key Features
| Feature | Description |
|---|---|
| Turbopack | Faster bundler (beta) |
| Server Actions | Form handling without API |
| Partial Prerendering | Static + Dynamic in one page |
| Improved Image | Better optimization |
Deployment
# Build for production
npm run build
# Start production server
npm start
# Or deploy to Vercel
npx vercel💡 Pro Tip: Use
next/imagefor automatic image optimization and better Core Web Vitals scores.
Published: December 20, 2024