Next.js Cheat Sheet

Project Setup

Create New App

Initialize a new Next.js application.

bash
npx create-next-app@latest

App Router

Page

The UI for a route.

tsx
// app/page.tsx
export default function Page() {
  return <h1>Hello, Next.js!</h1>;
}

Layout

Shared UI for a segment and its children.

tsx
// app/layout.tsx
export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <section>
      <nav></nav>
      {children}
    </section>
  );
}

Loading UI

Instant loading state for a segment.

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

Error Handling

Error UI for a segment.

tsx
// app/dashboard/error.tsx
'use client' // Error components must be Client Components

import { useEffect } from 'react';

export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    console.error(error);
  }, [error]);

  return (
    <div>
      <h2>Something went wrong!</h2>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

Components

Server Component

Default in App Router. Async/await support.

tsx
async function getData() {
  const res = await fetch('https://api.example.com/...');
  return res.json();
}

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

Client Component

Add 'use client' directive for interactivity.

tsx
'use client';

import { useState } from 'react';

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

Metadata

Static Metadata

Export a metadata object.

typescript
import type { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'My App',
  description: 'My application description',
};

export default function Page() {}

Dynamic Metadata

Generate metadata dynamically.

typescript
import type { Metadata } from 'next';

type Props = {
  params: { id: string };
};

export async function generateMetadata(
  { params }: Props
): Promise<Metadata> {
  const id = params.id;
  return {
    title: `Product ${id}`,
  };
}

export default function Page({ params }: Props) {}

Route Handlers

GET Request

Define a GET handler in route.ts.

typescript
// app/api/hello/route.ts
export async function GET(request: Request) {
  return Response.json({ message: 'Hello World' });
}

POST Request

Read the request body.

typescript
// app/api/hello/route.ts
export async function POST(request: Request) {
  const res = await request.json();
  return Response.json({ res });
}