Next.js Quick Reference

Concise guide to Next.js with practical examples

Next.js Quick Reference

Next.js is a powerful React framework for building fast, production-ready web applications with server-side rendering, static site generation, and more.

Installation

# Create a new Next.js app
npx create-next-app@latest my-app
cd my-app
npm run dev

Project Structure

my-app/
├── app/
│   ├── layout.tsx      # Root layout
│   ├── page.tsx        # Home page
│   └── about/
│       └── page.tsx    # /about page
├── components/
│   └── Header.tsx
├── public/
│   └── images/
└── package.json

Pages and Routing

// app/page.tsx
export default function Home() {
	return <h1>Welcome to Next.js!</h1>;
}

// app/about/page.tsx
export default function About() {
	return <h1>About Page</h1>;
}

Linking Between Pages

import Link from "next/link";

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

Static Assets

Place images and other static files in the public/ directory and reference them with /.

export default function Logo() {
	return <img src="/images/logo.png" alt="Logo" />;
}

Data Fetching (Server Components)

// app/page.tsx (using async/await)
async function getData() {
	const res = await fetch("https://jsonplaceholder.typicode.com/posts");
	return res.json();
}

export default async function Home() {
	const posts = await getData();
	return (
		<ul>
			{posts.slice(0, 5).map(post => (
				<li key={post.id}>{post.title}</li>
			))}
		</ul>
	);
}

API Routes

// app/api/hello/route.js
export async function GET() {
	return new Response(JSON.stringify({ message: "Hello from API!" }), {
		headers: { "Content-Type": "application/json" },
	});
}

Deploying

  • Deploy easily to Vercel (the creators of Next.js)
  • Or use your own server or static hosting

Best Practices

  1. Use the App Router for new projects.
  2. Keep components and pages small and focused.
  3. Use environment variables for secrets.
  4. Optimize images with next/image.
  5. Use TypeScript for type safety.

Resources