Next.js 16 cheatsheet

Next.js 16: Data and server code

6 common Next.js 16 tasks.

Fetch data in a server component

Server components can be async, so fetch data directly.

export default async function Page() {
  const res = await fetch("https://api.example.com/posts");
  const posts = await res.json();
  return <ul>{posts.map((p: { id: number; title: string }) => <li key={p.id}>{p.title}</li>)}</ul>;
}

Make a client component

Add this directive at the top of a file to use state, effects and browser APIs.

"use client";

Create a server action

A function marked "use server" runs on the server and can be called from forms.

"use server";

export async function createPost(formData: FormData) {
  const title = formData.get("title");
  // save the post
}

Redirect

Send the user to another route from server code.

import { redirect } from "next/navigation";

redirect("/login");

Refresh cached data

Invalidate cached data for a route after a change.

import { revalidatePath } from "next/cache";

revalidatePath("/posts");

Read a cookie

cookies() is async in current versions, so await it.

import { cookies } from "next/headers";

const token = (await cookies()).get("token")?.value;

Was this page helpful?