Nextjs

Next.js Cheatsheet

Next.js is a React framework with server-side rendering, routing, and optimization built-in. Master these patterns for production-ready apps.

Next.js is a React framework that provides server-side rendering, static site generation, file-based routing, API routes, and optimized performance out of the box. It's the go-to framework for production React applications.

NOTE: Tested using the latest version at time of writing, v14+ (App Router)

Getting Started

Create and run a Next.js project.

npx create-next-app@latest my-app
cd my-app
npm run dev              # Development server
npm run build            # Production build
npm start                # Production server

App Router (Recommended)

Modern routing with React Server Components.

// app/page.tsx - Home page
export default function Home() {
  return <h1>Home</h1>;
}

// app/about/page.tsx - About page
// app/blog/[slug]/page.tsx - Dynamic route
// app/dashboard/layout.tsx - Layout wrapper

Server Components (Default)

Components that render on the server.

// app/users/page.tsx
async function UsersPage() {
  const users = await fetch('https://api.example.com/users').then(r => r.json());
  
  return (
    <div>
      {users.map(user => (
        <div key={user.id}>{user.name}</div>
      ))}
    </div>
  );
}

Client Components

Components that need interactivity.

'use client';

import { useState } from 'react';

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

Route Handlers (API Routes)

Create API endpoints.

// app/api/users/route.ts
export async function GET() {
  return Response.json({ users: [] });
}

export async function POST(request: Request) {
  const body = await request.json();
  return Response.json({ success: true });
}

Dynamic Routes

Handle dynamic segments.

// app/blog/[slug]/page.tsx
export default async function BlogPost({ params }: { params: { slug: string } }) {
  const post = await getPost(params.slug);
  return <article>{post.content}</article>;
}

Metadata

Set page metadata.

// app/about/page.tsx
export const metadata = {
  title: 'About Us',
  description: 'Learn about our company',
};

Image Optimization

Optimize images automatically.

import Image from 'next/image';

<Image
  src="/hero.jpg"
  alt="Hero"
  width={800}
  height={600}
  priority
/>

Next.js simplifies React development with built-in routing, optimization, and server capabilities. Start with the App Router for new projects.

For full documentation, see https://nextjs.org/docs

Promote your content

Reach over 400,000 developers and grow your brand.

Join our developer community

Hang out with over 4,500 developers and share your knowledge.