Docsity

Complete NextJS Cheat Sheet, Cheat Sheet of Programming Languages

Toggle sidebar
bg1
Next.js Cheat Sheet
Quick reference for the Next.js App Router (v14/15+), React Server Components, and
TypeScript.
Create a Project
npx create-next-app@latest my-app
cd my-app && npm run dev
App Router File Conventions
File
Purpose
layout.tsx
Shared UI that wraps pages and persists across
navigation
page.tsx
Makes a route publicly accessible
loading.tsx
Suspense fallback shown while the route loads
error.tsx
Error boundary for the segment (must be a Client
Component)
not-found.tsx
UI for notFound() and unmatched routes
route.ts
API route handler (GET, POST, etc.)
template.tsx
Like layout, but re-mounts on navigation
middleware.ts
Runs before a request completes (project root or
src/ )
Next.js Cheat Sheet
Page 1 of 8
pf3
pf4
pf5
pf8

Partial preview of the text

Download Complete NextJS Cheat Sheet and more Cheat Sheet Programming Languages in PDF only on Docsity!

Next.js Cheat Sheet

Quick reference for the Next.js App Router (v14/15+), React Server Components, and

TypeScript.

Create a Project

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

App Router File Conventions

File Purpose

layout.tsx Shared UI that wraps pages and persists across

navigation

page.tsx Makes a route publicly accessible

loading.tsx Suspense fallback shown while the route loads

error.tsx Error boundary for the segment (must be a Client

Component)

not-found.tsx UI for^ notFound() and unmatched routes

route.ts API route handler (GET, POST, etc.)

template.tsx Like layout, but re-mounts on navigation

middleware.ts Runs before a request completes (project root or

src/ )

Routing

app/ page.tsx -> / about/page.tsx -> /about blog/[slug]/page.tsx -> /blog/hello-world (dynamic) docs/[...slug]/page.tsx -> /docs/a/b/c (catch-all) (marketing)/pricing/page.tsx -> /pricing (route group, no URL segment) _components/ -> private folder, not routable @modal/ -> parallel route slot

Pages, Layouts & Params

// app/layout.tsx export default function RootLayout({ children }: { children: React.ReactNode }) { return (

{children}

); }

// app/blog/[slug]/page.tsx (params is a Promise in Next 15) export default async function Post({ params, searchParams, }: { params: Promise<{ slug: string }>; searchParams: Promise<{ q?: string }>; }) { const { slug } = await params; const { q } = await searchParams; return {slug} {q}; }

Revalidation

import { revalidatePath, revalidateTag } from "next/cache";

revalidatePath("/blog"); revalidateTag("items");

Server Actions

// app/actions.ts "use server"; import { revalidatePath } from "next/cache";

export async function createTodo(formData: FormData) { const title = formData.get("title") as string; await db.todo.create({ data: { title } }); revalidatePath("/todos"); }

// Usage in a form (works without client JS)

Add

Validate and authorize inside every Server Action; treat them like public API endpoints.

Route Handlers (API)

// app/api/items/route.ts import { NextResponse } from "next/server";

export async function GET() { return NextResponse.json({ items: [] }); }

export async function POST(request: Request) { const body = await request.json(); return NextResponse.json(body, { status: 201 }); }

// Dynamic: app/api/items/[id]/route.ts export async function GET( _req: Request, { params }: { params: Promise<{ id: string }> } ) { const { id } = await params; return NextResponse.json({ id }); }

Navigation

import Link from "next/link"; import { redirect, notFound } from "next/navigation"; import { useRouter, usePathname, useSearchParams } from "next/navigation"; // client only

About

redirect("/login"); // in server code notFound(); // renders not-found.tsx

const router = useRouter(); router.push("/dashboard"); router.replace("/login"); router.refresh(); router.back();

Metadata & SEO

export const metadata = { title: "My App", description: "Built with Next.js", };

// Dynamic export async function generateMetadata({ params }) { const { slug } = await params; return { title: Post: ${slug} }; }

Middleware

// middleware.ts import { NextResponse, type NextRequest } from "next/server";

export function middleware(request: NextRequest) { if (!request.cookies.get("token")) { return NextResponse.redirect(new URL("/login", request.url)); } return NextResponse.next(); }

export const config = { matcher: ["/dashboard/:path*"] };

Environment Variables

.env.local for local secrets (never commit).

Variables prefixed with NEXT_PUBLIC_ are exposed to the browser; all others stay

server-side.

process.env.DATABASE_URL; // server only process.env.NEXT_PUBLIC_API_URL; // available in client code

next.config.js Basics

/** @type {import('next').NextConfig} */ const nextConfig = { images: { remotePatterns: [{ protocol: "https", hostname: "images.example.com" }] }, async redirects() { return [{ source: "/old", destination: "/new", permanent: true }]; }, }; module.exports = nextConfig;

Useful Commands

Common Pitfalls

Using hooks or browser APIs in a Server Component (add "use client" ).

Forgetting to await params / searchParams in Next 15.

Importing server-only code (DB clients, secrets) into Client Components.

Expecting fetch to be cached by default in newer versions.

Putting "use client" too high and bloating the JS bundle.

Command What it does

npm run dev Start dev server

npm run build Production build

npm start Run production server

npm run lint Run ESLint