Skip to content

Still Learning Next.js From Old Tutorials? A Lot of It No Longer Applies

By 34 min read

Next.js 16 changed how we build React apps: server components are the default, caching is explicit with 'use cache', and a page can be half static, half dynamic. Here is the full guide, from concepts to deployment.

id
Learn and knowing Next.js 16

Next.js is a React framework for building full-stack web apps, and as of October 2026 its latest version, Next.js 16.4, brings the biggest shift since the App Router was born: server components are the default, caching is explicit through 'use cache', and a single page can be half static and half dynamic. I've tested every piece of code below on Next.js 16.4.2, so you can use it as is.

If you've ever built a React app from scratch, you've probably had this moment: the app runs smoothly on your laptop, the animations are buttery, every button works. Then, out of curiosity, you open view-source, and all you find is <div id="root"></div> plus a pile of script tags. Sure, Google can run JavaScript now, but it gets queued, it isn't instant, and not every crawler is as patient as Googlebot. And that's before we even get to routing, bundle splitting, image optimization, and the classic question: where should this database call actually live?

Next.js was born to answer those problems. But today's Next.js is very different from the one people used to describe as "React that can do SSR", and a lot of the tutorials floating around simply don't apply anymore.

So what I want to unpack here is less about what Next.js can do and more about why it works the way it does. You can read the feature list in the docs yourself, but understanding the reasoning is what tells you where to look when you hit a weird error. The running example is a simple blog that pulls data from a headless CMS, complete with comments, SEO, and a deployment setup.

Grab a coffee, this one's long. Let's take it apart piece by piece.

What Is Next.js?

Next.js is a React-based framework developed by Vercel and first released in October 2016. If React is the engine, Next.js is the whole car. React knows how to build an interface out of components, but it doesn't care which URL shows which page, where the data comes from, or how to get the page to the browser as fast as possible. All of that is Next.js's job.

Concretely, Next.js gives you:

  • Routing based on your folder structure, with no manual router configuration.
  • Server rendering, so the HTML that reaches the browser already contains the content.
  • A way to fetch and mutate data straight from your components, without building a separate API for everything.
  • A caching system you can control down to the component level.
  • Built-in optimization for images, fonts, and scripts.
  • A production build you can deploy to Vercel, your own server, or a container.

How is Next.js different from plain React?

React on its own, say through Vite, usually runs as a Single Page Application. The browser downloads the JavaScript, and that JavaScript builds the page. The consequence is a blank screen until the script finishes loading, and every data fetch happens in the browser.

Next.js flips that order. The page is rendered on the server first, the HTML gets sent, and then React in the browser "brings to life" the parts that are interactive. On top of that, ever since React introduced Server Components, some components run only on the server, and their code never ships to the browser at all. React provides the concept, but it needs a framework to actually run it, and Next.js is the most mature implementation out there right now.

Where Next.js Stands as of October 2026

This matters, because plenty of tutorials on the internet still use the old way of doing things. A few milestones worth knowing:

  • Next.js 16 shipped on October 21, 2025. Turbopack became the default bundler, middleware.ts was replaced by proxy.ts, Cache Components were introduced, params and cookies() must now be accessed asynchronously, and the minimum Node.js version went up to 20.9.
  • Next.js 16.3 shipped in August 2026, bringing Instant Navigations, Partial Prefetching, root params, and catchError for more flexible error boundaries.
  • Next.js 16.4 shipped on October 6, 2026. Cache Components are now recommended for every app and enabled by default in create-next-app. The Next.js team has also said this model will become the default in Next.js 17.

The Next.js team was pretty clear about the direction in the 16.4 announcement:

"we're excited to recommend Cache Components as the best choice for every Next.js app."

So if you come across a tutorial that still uses getServerSideProps, export const revalidate = 60, or a single-argument revalidateTag('posts'), treat it as a history lesson. The concepts are still worth understanding, but the way you write them has changed.

A Bit of History: Why Next.js Looks the Way It Does

Knowing how Next.js got here makes a lot of its design decisions click.

Back in the day, the web was built with servers that rendered HTML, whether in PHP, Rails, or something else. Every click meant a full page load. Simple and fast on the first load, but it felt rigid.

Then came the Single Page Application era. Everything moved to the browser, navigation got smooth, but the first load got heavy and SEO became its own headache. Early versions of Next.js bridged those two worlds with the Pages Router, using functions like getServerSideProps and getStaticProps to decide when a page gets rendered.

Next.js 13, released in late 2022, introduced the App Router, built on React Server Components, and declared it stable in version 13.4 in May 2023. It was a huge leap, but it came with one problem that drove a lot of people up the wall: implicit caching. fetch was cached automatically, pages could turn static without you noticing, and data you'd already changed in the database just refused to show up on screen.

I was one of the people scratching their heads back then. The database was updated, I refreshed the page over and over, and the data was still the old one. It turned out fetch had been cached quietly and the page had become static at build time. It felt like asking a friend "have you eaten?", hearing "yep", and then finding out that was yesterday's answer. Experiences like that are why so many developers called the App Router "unpredictable".

Next.js 15 started fixing it by no longer caching fetch by default. Next.js 16 finished the job with Cache Components: everything is dynamic by default, and you explicitly decide which parts get cached. 16.3 and 16.4 doubled down on that direction. In short, Next.js is going back to a more honest principle: what you write is what happens.

Setting Up Your First Project

Make sure your Node.js is at least version 20.9. Then run:

Bash
npx create-next-app@latest learn-next
cd learn-next
npm run dev

If you go with the recommended settings, you'll get TypeScript, Tailwind CSS, the App Router, Turbopack, plus Cache Components and Partial Prefetching already turned on. Check next.config.ts, and it should look roughly like this:

TypeScript
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true,
}

export default nextConfig

For an older project you're migrating, you can add these two options by hand. Set partialPrefetching explicitly, because if you leave it out, Next.js will log a warning.

Oh, and one small thing that might confuse you: after running next dev, an AGENTS.md file may show up in your project root. It's not junk. Since 16.3, Next.js writes instructions to that file so AI coding agents read the docs that match the Next.js version in your project. Use it or ignore it, your call.

The initial project structure looks something like this:

learn-next/
├── app/
│   ├── layout.tsx
│   ├── page.tsx
│   └── globals.css
├── public/
├── next.config.ts
├── package.json
└── tsconfig.json

App Router: Folders Are Routes

The most basic idea in the App Router: the folder structure inside app/ is your URL structure. Folders define route segments, and specially named files inside them define what gets shown.

The special files you'll use most often:

  • page.tsx is the page content. A folder only becomes a reachable URL once it has this file.
  • layout.tsx wraps a page and every page beneath it. Layouts don't re-render when you navigate between the pages under them, so their state is preserved.
  • loading.tsx is the temporary UI shown while the page loads its data.
  • error.tsx catches errors in that segment so they don't take down the whole app.
  • not-found.tsx shows up when you call notFound().
  • route.ts is an HTTP endpoint, which we'll cover in the Route Handlers section later.

For the blog we're going to build, the structure looks like this:

app/
├── layout.tsx
├── page.tsx
├── robots.ts
├── sitemap.ts
├── api/
│   └── revalidate/
│       └── route.ts
└── blog/
    ├── page.tsx
    └── [slug]/
        ├── page.tsx
        ├── actions.ts
        ├── comments.tsx
        └── comment-form.tsx

The [slug] folder with square brackets is a dynamic segment. The URL /blog/learn-next fills slug with learn-next. There are a few other variations you should know:

  • [...slug] catches all the remaining segments, like /docs/a/b/c.
  • (marketing) in regular parentheses is a route group. The folder doesn't appear in the URL, and its job is to group routes that share a layout.
  • _components with a leading underscore is a private folder that will never become a route. It's a good place for components used only in that segment.

Now the root layout. File app/layout.tsx:

TypeScript
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import './globals.css'

const inter = Inter({ subsets: ['latin'], display: 'swap' })

export const metadata: Metadata = {
  metadataBase: new URL('https://example.com'),
  title: { default: 'Dev Notes', template: '%s · Dev Notes' },
  description: 'Notes on web development, from frontend to infrastructure.',
}

export default function RootLayout({ children }: LayoutProps<'/'>) {
  return (
    <html lang="en" className={inter.className}>
      <body>{children}</body>
    </html>
  )
}

Notice LayoutProps<'/'>. It's a global type that Next.js generates automatically while next dev or next build runs, so you don't need to import anything. Its sibling, PageProps<'/blog/[slug]'>, shows up later. The nice part is that if you rename a dynamic segment, TypeScript immediately complains everywhere it matters.

Oh, and metadataBase gets forgotten a lot. Without it, relative Open Graph image URLs can't be turned into absolute ones, and link previews on social media may fail to show up.

Server Components and Client Components

If there's one part of this article you really need to nail, it's this one. Almost all the confusion around modern Next.js starts here.

Every component is a Server Component unless you say otherwise

In the App Router, every component is a Server Component by default. That means:

  • It runs on the server, at build time or at request time.
  • Its code is never sent to the browser. A heavy library used only there, say a Markdown parser, adds exactly zero bytes to your bundle.
  • It can be async and can talk directly to a database, the file system, or an API with secret credentials.
  • It can't use useState, useEffect, event handlers like onClick, or browser APIs like window and localStorage.

A Client Component is one marked with 'use client' at the very top of the file. It gets sent to the browser and can be interactive.

There's one misconception I run into a lot, even from developers who've used Next.js for a while: Client Components are still rendered on the server for their initial HTML. 'use client' doesn't mean "render only in the browser". It means "this component also needs to be sent to the browser so it can be interactive". The HTML still comes from the server, and then React in the browser wires up the event handlers. That process is called hydration.

When should you use 'use client'?

Use 'use client' when the component needs any of these:

  • State or lifecycle: useState, useReducer, useEffect, and friends.
  • Event handlers: onClick, onChange, onSubmit with logic that runs in the browser.
  • Browser APIs: window, document, localStorage, navigator.clipboard, geolocation.
  • Third-party libraries that rely on any of the above.

Take a copy-link button. It needs navigator.clipboard and state, so it has to be a Client Component. File app/blog/[slug]/copy-link.tsx:

TypeScript
'use client'

import { useState } from 'react'

export function CopyLink({ url }: { url: string }) {
  const [copied, setCopied] = useState(false)

  return (
    <button
      type="button"
      onClick={async () => {
        await navigator.clipboard.writeText(url)
        setCopied(true)
        setTimeout(() => setCopied(false), 1500)
      }}
    >
      {copied ? 'Copied' : 'Copy link'}
    </button>
  )
}

You use it from a Server Component like any other component, just <CopyLink url={...} />. The only thing that ships to the browser is the code for this tiny button, not the whole article page.

'use client' is a boundary, not a label

This is a detail people often miss. 'use client' marks the point where code starts going into the browser bundle. Everything that file imports becomes client code too.

The classic mistake: putting 'use client' at the very top layout because you need one small piece of state, say for a mobile menu. The result is that the entire component tree below it gets dragged into the client, exactly like one person inviting you to lunch and the whole department tagging along. Every benefit of Server Components goes out the window. The fix is usually the same: push 'use client' as far toward the leaves of the tree as you can. Is the menu button the only interactive part? Then only the menu button becomes a Client Component.

Component tree from layout.tsx: Server Components render on the server with no JavaScript in the browser, only Client Components like Menu and CopyLink are shipped

The forgotten pattern: Server Components as children

What if you need an interactive wrapper, like a panel that opens and closes, but its content fetches data on the server? A Client Component can't import a Server Component. It can, however, receive one through children.

File app/_components/collapsible.tsx:

TypeScript
'use client'

import { type ReactNode, useState } from 'react'

export function Collapsible({ title, children }: { title: string; children: ReactNode }) {
  const [open, setOpen] = useState(false)

  return (
    <section>
      <button type="button" aria-expanded={open} onClick={() => setOpen((v) => !v)}>
        {title}
      </button>
      {open ? children : null}
    </section>
  )
}

Then, in a Server Component:

TypeScript
<Collapsible title="Table of contents">
  <TableOfContents slug={slug} />
</Collapsible>

TableOfContents stays a Server Component. It's rendered on the server, and the result is handed to Collapsible as children. Not a single line of TableOfContents ends up in the browser bundle. The pattern looks trivial, but it's one of the most useful techniques for keeping your bundle small.

What can you pass from server to client?

Props going from a Server Component to a Client Component have to be serializable, because the data crosses the network. These are safe:

  • Strings, numbers, booleans, null, and undefined.
  • Plain arrays and objects.
  • Date, Map, Set, and BigInt.
  • Promises, which you can unwrap on the client with use().
  • JSX elements, including Server Components passed as children.

What doesn't work: regular functions and class instances. The exception is Server Functions, which we'll get to in the Server Actions section.

Keep server code on the server

As a project grows, so does the risk of server code being accidentally imported from a Client Component. If that happens to a file holding credentials, the damage can be serious. To prevent it, install the server-only package and import it in files that are meant for the server only:

Bash
npm install server-only

Now let's build the layer that talks to the CMS. File lib/cms.ts:

TypeScript
import 'server-only'

const base = process.env.CMS_URL
const token = process.env.CMS_TOKEN

export async function cms<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`${base}${path}`, {
    ...init,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
      ...init?.headers,
    },
  })
  if (!res.ok) throw new Error(`CMS responded with ${res.status} for ${path}`)
  return res.json() as Promise<T>
}

If a Client Component ever imports this file, the build fails right away with a clear message. Far better to find out at build time than to have your CMS token leak into the browser.

As for environment variables, the rule is simple: only variables prefixed with NEXT_PUBLIC_ are sent to the browser. CMS_TOKEN above is safe because it doesn't have that prefix. Never put a secret in a NEXT_PUBLIC_ variable, because its value gets baked straight into JavaScript that anyone can read.

Fetching Data Without useEffect

In classic React, the data-fetching pattern usually goes like this: render an empty component, run useEffect, call the API, store the result in state, render again. In a Server Component, all of that gets replaced by a single await.

File lib/posts.ts:

TypeScript
import 'server-only'
import { cacheLife, cacheTag } from 'next/cache'
import { cms } from './cms'

export type Post = {
  slug: string
  title: string
  excerpt: string
  content: string
  cover?: string
  publishedAt: string
  updatedAt: string
}

export async function getPosts() {
  'use cache'
  cacheLife('hours')
  cacheTag('posts')
  return cms<Post[]>('/posts?sort=-publishedAt')
}

export async function getPost(slug: string) {
  'use cache'
  cacheLife('days')
  cacheTag('posts', `post-${slug}`)
  const [post] = await cms<Post[]>(`/posts?slug=${encodeURIComponent(slug)}`)
  return post ?? null
}

Ignore 'use cache', cacheLife, and cacheTag for now. We'll cover them properly in the caching section. Next up is the article list page, file app/blog/page.tsx:

TypeScript
import type { Metadata } from 'next'
import Link from 'next/link'
import { getPosts } from '@/lib/posts'

export const metadata: Metadata = {
  title: 'Blog',
  description: 'Everything I have written about web development.',
}

export default async function BlogPage() {
  const posts = await getPosts()

  return (
    <main>
      <h1>Blog</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.slug}>
            <Link href={`/blog/${post.slug}`}>{post.title}</Link>
            <p>{post.excerpt}</p>
          </li>
        ))}
      </ul>
    </main>
  )
}

No useEffect, no loading state, no middleman API endpoint. The component asks for data, waits, and renders. The code is shorter, and more importantly, it's easier to read six months from now.

Watch out for waterfalls

Because await is so easy to write, there's a trap that shows up a lot. Look at this code:

TypeScript
export default async function Page() {
  const posts = await getPosts()
  const categories = await getCategories()
  const popular = await getPopularPosts()

  return <Home posts={posts} categories={categories} popular={popular} />
}

These three requests don't depend on each other, but they run one after another. If each one takes 200 milliseconds, the total is 600 milliseconds. That's long enough for your users to blame their Wi-Fi when it's really your code. This is what's called a waterfall.

The simplest fix is to run them in parallel:

TypeScript
export default async function Page() {
  const [posts, categories, popular] = await Promise.all([
    getPosts(),
    getCategories(),
    getPopularPosts(),
  ])

  return <Home posts={posts} categories={categories} popular={popular} />
}

Now the total is roughly as long as the slowest request. But there's an even better option: split them into separate components that each fetch their own data, then wrap them in <Suspense>. That way the fast parts can show up first without waiting for the slow ones. More on that in the next section.

Three sequential data requests take 600 ms, while the parallel version with Promise.all takes 200 ms, a 400 ms difference caused by await order


React.cache for per-request data

Some data gets used in many places within a single request but must never be cached across users. The most common example is the login session. For this, use cache from React. It makes sure the same function with the same arguments runs only once per request.

File lib/session.ts:

TypeScript
import 'server-only'
import { cookies } from 'next/headers'
import { cache } from 'react'
import { cms } from './cms'

export type User = { id: string; name: string }

export const getSession = cache(async () => {
  const token = (await cookies()).get('session')?.value
  if (!token) return null
  return cms<User>('/users/me', { headers: { Authorization: `Bearer ${token}` } }).catch(() => null)
})

Call it in the header, the sidebar, and a Server Action within the same request, and the CMS still gets hit only once. Keep this separate from 'use cache' in your head: React.cache lives for a single request, while 'use cache' survives across requests.

Streaming and Suspense: Don't Make the Page Wait for the Slowest Part

Picture an article page. The article body comes back in 50 milliseconds, but the comment list takes 800 milliseconds because the comment service is slow. Without streaming, users stare at a blank screen for 800 milliseconds. With streaming, the article shows up first and the comments follow.

The way to do it is to wrap the slow part in <Suspense>:

TypeScript
import { Suspense } from 'react'

export default function Page() {
  return (
    <>
      <ArticleBody />
      <Suspense fallback={<p>Loading comments…</p>}>
        <Comments />
      </Suspense>
    </>
  )
}

The server sends the article HTML along with the text "Loading comments…" first. Once the comment data is ready, the server sends the next chunk of HTML in the same response, and React swaps the fallback for the real content. There's no extra request from the browser. It's all one HTTP response, flowing.

Streaming with Suspense: the shell and fallback are sent first, then the comments arrive in the same HTTP response without another request

A loading.tsx file is really just a shortcut for the same pattern, except it wraps the whole page. File app/blog/loading.tsx:

TypeScript
export default function Loading() {
  return <p>Loading article…</p>
}

My advice: use more granular <Suspense> boundaries wherever you can. loading.tsx is a fine safety net, but if your only Suspense boundary sits at the route level, one slow component will hold up the entire page.

Caching in Next.js 16: Cache Components and 'use cache'

This is the part that changed the most, and in my opinion the part most worth understanding deeply.

The new mental model

With Cache Components, every part of a page falls into one of three categories:

  1. Static. Components that don't fetch any async data, or only use values that are guaranteed to be the same every time. They're rendered at build time.
  2. Cached. Components or functions marked with 'use cache'. Their output is stored and reused for as long as the cache lifetime you set.
  3. Dynamic at request time. Components that fetch data without caching, or read request-specific data like cookies(), headers(), and searchParams. These must be wrapped in <Suspense>.

At build time, Next.js renders the component tree and produces what's called a static shell: every static part, every cached part, plus the fallback of every <Suspense>. That shell can be served straight from a CDN in milliseconds. The dynamic parts then stream in on the same response. This technique is called Partial Prerendering, and with Cache Components it's the default behavior. The full explanation is in the Next.js caching guide.

Anatomy of a page with Cache Components: static parts render at build time, use cache parts are stored, and dynamic parts inside Suspense stream at request time

Before, Next.js had to pick: this page is either static or dynamic, with no middle ground. A single call to cookies() anywhere could turn the whole page dynamic. Now static and dynamic can live side by side on the same page.

'use cache' at the data level and the UI level

You can put 'use cache' on a data-fetching function, like getPosts earlier, or on a component:

TypeScript
import { cacheLife } from 'next/cache'

async function PopularPosts() {
  'use cache'
  cacheLife('hours')

  const posts = await getPopularPosts()

  return (
    <ol>
      {posts.map((post) => (
        <li key={post.slug}>{post.title}</li>
      ))}
    </ol>
  )
}

Function arguments and any values captured from outside automatically become part of the cache key. getPost('learn-next') and getPost('css-tips') each get their own cache entry, without you having to manage the keys by hand.

Setting cache lifetimes with cacheLife

Always pair 'use cache' with cacheLife. Without it, the default profile applies, and the behavior gets hard to predict, especially with nested caches. Every profile has three numbers:

  • stale: how long the browser can use cached data without asking the server.
  • revalidate: after this time, the next request still gets the old data, but the server refreshes the cache in the background.
  • expire: if there are no requests for this long, the next request has to wait for fresh data.
Cache lifetime with cacheLife days: for five minutes the browser uses its own copy, then the server serves from cache, revalidates in the background after a day, and waits for fresh data after a week

The built-in profiles, according to the cacheLife documentation:

  • default: stale 5 minutes, revalidate 15 minutes, never expires.
  • seconds: stale 30 seconds, revalidate 1 second, expire 1 minute. For real-time data like live scores.
  • minutes: stale 5 minutes, revalidate 1 minute, expire 1 hour. For feeds that change often.
  • hours: stale 5 minutes, revalidate 1 hour, expire 1 day.
  • days: stale 5 minutes, revalidate 1 day, expire 1 week. A good fit for blog posts.
  • weeks: stale 5 minutes, revalidate 1 week, expire 30 days.
  • max: stale 5 minutes, revalidate 30 days, expire 1 year. For content that almost never changes.

If none of them fit, create your own profile in next.config.ts:

TypeScript
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true,
  cacheLife: {
    editorial: {
      stale: 600,
      revalidate: 3600,
      expire: 86400,
    },
  },
}

export default nextConfig

Then call it with cacheLife('editorial'). One note: a very short-lived cache, like the seconds profile, doesn't make it into the static shell. It's treated as a dynamic part, so it still needs to be wrapped in <Suspense>.

Invalidating with tags: revalidateTag, updateTag, and refresh

Waiting for a cache to expire on its own often isn't enough. When an editor publishes a new article, you want it to show up right away. That's where cacheTag comes in. We already tagged things with posts and post-${slug} in lib/posts.ts. Now we just need to throw out the cache by tag.

There are three functions, each with its own role:

  • revalidateTag(tag, profile) marks the cache as stale with stale-while-revalidate behavior. The next visitor still sees the old version for a moment, while the new version is prepared in the background. This suits public content like articles. Since Next.js 16, the second argument is required, and the 'max' profile is the recommended choice for most cases.
  • updateTag(tag) expires the cache immediately and makes sure the same request already reads fresh data. It only works inside a Server Action. It's ideal for user interactions, like making sure users see their own comment right after posting it.
  • refresh() doesn't touch the cache at all. It only refreshes the parts of the page that aren't cached. Also Server Action only.

You'll see them in action in the Server Actions and Route Handlers sections shortly.

Request-specific data has to be wrapped in Suspense

Here's a rule you'll bump into a lot: any component that reads cookies(), headers(), searchParams, or params that aren't known at build time has to live inside <Suspense>. If you forget, the Next.js dev overlay shows an insight called blocking-route, complete with a suggested fix.

It may feel like a chore at first. I actually like this rule, though, because it forces us to be aware of which parts are dynamic. In the old days, one cookies() call tucked into a header component could quietly turn the whole site dynamic, and you'd only find out when the server bill ballooned. Now Next.js complains right from the start, while you're still on your laptop.

Request data also can't be read directly inside 'use cache', because a cached result is shared by many users. The pattern is to read the value outside, then pass it in as an argument.

TypeScript
import { cacheLife } from 'next/cache'
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { getPostsByTopic } from '@/lib/posts'

export default function Page() {
  return (
    <Suspense fallback={<p>Loading recommendations…</p>}>
      <Recommendations />
    </Suspense>
  )
}

async function Recommendations() {
  const topic = (await cookies()).get('topic')?.value ?? 'general'
  return <CachedRecommendations topic={topic} />
}

async function CachedRecommendations({ topic }: { topic: string }) {
  'use cache'
  cacheLife('hours')
  const posts = await getPostsByTopic(topic)
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.slug}>{post.title}</li>
      ))}
    </ul>
  )
}

topic becomes part of the cache key. Every user with the same topic shares a single cache entry, while reading the cookie still happens per request.

Random values and the current time

One more thing that catches people off guard: Math.random(), Date.now(), new Date() with no arguments, and crypto.randomUUID() also need explicit handling. Leave them alone and their values get "frozen" at build time. You have two options: call await connection() from next/server before using them, and wrap the component in <Suspense>, so the value is generated fresh on every request. Or put them inside 'use cache' if it's fine for everyone to see the same value until the cache refreshes.

Where is the cache actually stored?

This question rarely gets discussed, yet it matters the moment you self-host:

  • Prerendered HTML is stored on disk when self-hosting, or in the platform's storage behind a CDN.
  • Runtime 'use cache' results are stored in memory by default, per server instance. If you run three containers, each has its own cache. In serverless environments, that memory doesn't stick around for long either.
  • The browser keeps cached results according to the stale value for later navigations.

If you need a cache shared across many instances, there's a 'use cache: remote' variant that uses a shared cache handler, Redis for example. There's also 'use cache: private' for personal data that's only stored in the browser. One more thing: all of these caches are tied to a single deployment. The moment you deploy a new version, the cache starts from scratch.

Putting the Article Page Together

Now let's combine everything in the article detail page. File app/blog/[slug]/page.tsx:

TypeScript
import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { Suspense } from 'react'
import { getPost, getPosts } from '@/lib/posts'
import { CommentForm } from './comment-form'
import { Comments } from './comments'
import { CopyLink } from './copy-link'

export async function generateStaticParams() {
  const posts = await getPosts()
  return posts.slice(0, 20).map((post) => ({ slug: post.slug }))
}

export async function generateMetadata({ params }: PageProps<'/blog/[slug]'>): Promise<Metadata> {
  const { slug } = await params
  const post = await getPost(slug)
  if (!post) return {}

  return {
    title: post.title,
    description: post.excerpt,
    alternates: { canonical: `/blog/${post.slug}` },
    openGraph: {
      type: 'article',
      title: post.title,
      description: post.excerpt,
      publishedTime: post.publishedAt,
      modifiedTime: post.updatedAt,
      images: post.cover ? [post.cover] : [],
    },
  }
}

export default function Page({ params }: PageProps<'/blog/[slug]'>) {
  return (
    <Suspense fallback={<p>Loading article…</p>}>
      <Article params={params} />
    </Suspense>
  )
}

async function Article({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const post = await getPost(slug)
  if (!post) notFound()

  const published = new Intl.DateTimeFormat('en-US', { dateStyle: 'long' }).format(new Date(post.publishedAt))

  return (
    <article>
      <h1>{post.title}</h1>
      <time dateTime={post.publishedAt}>{published}</time>
      <CopyLink url={`https://example.com/blog/${post.slug}`} />
      <div dangerouslySetInnerHTML={{ __html: post.content }} />
      <section>
        <h2>Comments</h2>
        <Suspense fallback={<p>Loading comments…</p>}>
          <Comments slug={slug} />
        </Suspense>
        <CommentForm slug={slug} />
      </section>
    </article>
  )
}

A few things worth pointing out:

  • params is now a Promise. Since Next.js 16, synchronous access to params, searchParams, cookies(), and headers() has been removed.
  • generateStaticParams prerenders the 20 latest articles at build time. Other articles don't error out. Their first visitor gets the shell right away, then the full version is built in the background and stored for the next visitor. This is the new flavor of Incremental Static Regeneration that arrived in 16.3.
  • The page component itself is synchronous, and params is only awaited inside <Suspense>. That way the page skeleton still makes it into the static shell even when the slug isn't known at build time.
  • getPost is called twice, in generateMetadata and in Article, but the CMS only gets hit once because the result is cached.
  • dangerouslySetInnerHTML is used because the content comes from your own CMS. If outsiders can write that content, sanitize it before rendering.
  • notFound() inside <Suspense> has a behavior you should know about. When I tested it, a slug that doesn't exist returned a 200 status to regular browsers, because the HTTP status had already been sent before notFound() was called. It still renders the 404 page, and Next.js automatically adds <meta name="robots" content="noindex">. Googlebot, on the other hand, is recognized as a crawler and rendered without streaming, so it gets a real 404 status. It's safe for SEO, but don't be surprised if your monitoring logs a 200 for pages that don't actually exist.

The comments component, file app/blog/[slug]/comments.tsx:

TypeScript
import { cacheLife, cacheTag } from 'next/cache'
import { cms } from '@/lib/cms'

type Comment = { id: string; author: string; body: string }

export async function Comments({ slug }: { slug: string }) {
  'use cache'
  cacheLife('minutes')
  cacheTag(`comments-${slug}`)

  const comments = await cms<Comment[]>(`/comments?post=${encodeURIComponent(slug)}`)
  if (!comments.length) return <p>No comments yet. Quieter than a class group chat after graduation.</p>

  return (
    <ul>
      {comments.map((comment) => (
        <li key={comment.id}>
          <strong>{comment.author}</strong>
          <p>{comment.body}</p>
        </li>
      ))}
    </ul>
  )
}

Server Actions: Mutating Data Without Building Your Own API

A Server Action is an async function that runs on the server but can be called straight from a form or a component in the browser. All you do is mark the function with 'use server'. Next.js takes care of creating the endpoint, serializing the data, and making the call.

The comment form

File app/blog/[slug]/actions.ts:

TypeScript
'use server'

import { updateTag } from 'next/cache'
import { cms } from '@/lib/cms'
import { getSession } from '@/lib/session'

type CommentState = { error: string | null }

export async function addComment(slug: string, _prev: CommentState, formData: FormData): Promise<CommentState> {
  const session = await getSession()
  if (!session) return { error: 'Please sign in before commenting.' }

  const body = String(formData.get('body') ?? '').trim()
  if (body.length < 3 || body.length > 2000) return { error: 'Comments must be between 3 and 2,000 characters.' }

  await cms('/comments', {
    method: 'POST',
    body: JSON.stringify({ post: slug, body, author: session.id }),
  })

  updateTag(`comments-${slug}`)
  return { error: null }
}

Then the form itself, file app/blog/[slug]/comment-form.tsx:

TypeScript
'use client'

import { useActionState } from 'react'
import { addComment } from './actions'

export function CommentForm({ slug }: { slug: string }) {
  const [state, action, pending] = useActionState(addComment.bind(null, slug), { error: null })

  return (
    <form action={action}>
      <textarea name="body" required minLength={3} maxLength={2000} />
      {state.error ? <p role="alert">{state.error}</p> : null}
      <button type="submit" disabled={pending}>
        {pending ? 'Posting…' : 'Post comment'}
      </button>
    </form>
  )
}

Here's the flow: the user hits the button, useActionState calls addComment on the server with slug already bound through bind, and the server saves the comment and then calls updateTag. Because updateTag has read-your-writes semantics, the response from that Server Action already carries the latest comment list. Users see their own comment immediately, with no reload, no manual fetch, and no global state.

Server Action flow: the form is submitted, the session is checked, input is validated, data is saved to the CMS, and updateTag runs on the server, so the browser waits for a single response before the new comment shows

Compare that with the old way: build an API endpoint, call it with fetch from the client, handle loading and errors, then re-sync local state. That can easily be three times the code.

Server Actions are public endpoints

This is the part people underestimate the most. Every Server Action is, at its core, an HTTP POST endpoint that anyone can call, not just the form you built. Hiding a button from signed-out users doesn't mean the action is protected.

So in every Server Action, no exceptions:

  • Check authentication. Who's calling?
  • Check authorization. Are they allowed to do this to this data?
  • Validate input. Everything in FormData comes from the client and can't be trusted. For more complex forms, libraries like Zod or Valibot help a lot.

Next.js does add some safety layers, like non-deterministic action IDs and encrypted closure variables. But those are extra layers, not a replacement for the checks above.

A deployment lesson: "Failed to find Server Action"

There's one problem you're almost guaranteed to hit once you self-host with Docker, and the docs only start to feel relevant after it bites you.

It happened to me on a personal project deployed to a VPS through containers. After deploying a new version, the save button in the dashboard suddenly stopped doing anything. The server logs were full of "Failed to find Server Action". The cause: a browser tab that was still open held action IDs from the old build, while the server was already running a new build with different IDs.

Next.js generates Server Action IDs and encrypts their data with a key that can differ on every build. The fix is to set a consistent encryption key through the NEXT_SERVER_ACTIONS_ENCRYPTION_KEY environment variable. The key is a base64 string that decodes to 16, 24, or 32 bytes:

Bash
openssl rand -base64 32

The part people often miss: this variable has to be available at build time, not just at runtime, because the key gets embedded in the build output. If you use a platform like Dokploy or Coolify, that means adding the key as a build argument, not just to the runtime environment. I spent a while confused about why my build suddenly finished way faster than usual while the problem still wasn't fixed. Turns out the key was only being read at runtime.

A consistent key is also a must if you run several instances behind a load balancer, so every instance can read the same action data. But remember, actions that actually changed or got removed in the new build still won't be found by old tabs. So handle that failure in the UI anyway, for example with a message asking the user to reload the page, and keep the user's draft in the browser so their writing doesn't vanish. On Vercel, this problem is handled by a feature called Skew Protection.

Route Handlers: When You Actually Need an HTTP Endpoint

Server Actions are great for mutations triggered from your own UI. But sometimes you need a real HTTP endpoint: a webhook from another service, an API for a mobile app, or an RSS feed. That's what Route Handlers are for, which are route.ts files that export functions named after HTTP methods.

The most useful example for our blog: a webhook the CMS calls every time an article is published or updated. File app/api/revalidate/route.ts:

TypeScript
import { revalidateTag } from 'next/cache'
import type { NextRequest } from 'next/server'

export async function POST(request: NextRequest) {
  if (request.headers.get('x-webhook-secret') !== process.env.WEBHOOK_SECRET) {
    return Response.json({ ok: false }, { status: 401 })
  }

  const { slug } = (await request.json()) as { slug?: string }

  revalidateTag('posts', 'max')
  if (slug) revalidateTag(`post-${slug}`, 'max')

  return Response.json({ ok: true })
}

Set up your CMS to send a POST to /api/revalidate with the secret header every time content changes. Now articles can be cached for days and still show the latest version a few seconds after the editor hits publish. For a content site, that's the ideal combo: fast like a static site, fresh like a dynamic one.

One mistake I see a lot: a Server Component calling its own app's Route Handler through fetch('/api/...'). That's a wasted network round trip. A Server Component is already running on the server, so just call the data function directly.

proxy.ts: The Bouncer at the Door

In Next.js 16, middleware.ts was renamed to proxy.ts, and the exported function was renamed to proxy. The logic stays the same. The difference is that proxy.ts runs on the Node.js runtime, and the name was chosen on purpose to make its role clear: a layer in front of your app that intercepts requests before they reach a route. middleware.ts still works for Edge runtime use cases, but it's deprecated.

Here's an example that redirects users without a session cookie to the sign-in page. File proxy.ts in the project root:

TypeScript
import { type NextRequest, NextResponse } from 'next/server'

export function proxy(request: NextRequest) {
  if (!request.cookies.has('session')) {
    const url = new URL('/sign-in', request.url)
    url.searchParams.set('next', request.nextUrl.pathname)
    return NextResponse.redirect(url)
  }
  return NextResponse.next()
}

export const config = {
  matcher: ['/dashboard/:path*'],
}

Notice that this only checks whether the cookie exists, not whether the session is valid. And that's how it should be. A proxy is good for light, optimistic checks: redirects, rewrites, setting headers, or routing by language. Don't make it your only line of defense.

There's a real reason behind that advice. In March 2025, a vulnerability tracked as CVE-2025-29927 was found that let attackers skip middleware entirely just by adding one special header to the request. Apps that put all their authorization checks in middleware were left wide open. Apps that still checked the session close to their data, in Server Components, Server Actions, and Route Handlers, were relatively safe.

Proxy isn't the only guard: a request that gets past proxy.ts is still checked by getSession before it touches any data

The principle: verify access as close to the data as possible. Functions like the getSession() we wrote earlier should be called everywhere sensitive data is accessed.

SEO in Next.js: Metadata, Sitemaps, and Structured Data

SEO is one of the main reasons people pick Next.js. Honestly, SEO is more of a product concern than a content-team concern, and I wrote about that at length in News Media Needs SEO, But Not an SEO Team. The foundation is already solid because the HTML is rendered on the server. There are still a few things you need to set up yourself, though.

Metadata

We've already seen two ways to do it: a static metadata object in the layout and generateMetadata in dynamic pages. Next.js merges metadata from layouts down to pages in layers. That's why the title.template in the root layout automatically appends " · Dev Notes" to every page title.

There's an interesting detail about metadata in the streaming era. With Partial Prerendering, dynamic metadata can arrive after the shell has been sent. Some crawlers can't handle that and need the metadata in the <head> from the start. Next.js detects those crawlers by their user agent and renders the full page for them. The catch is that your data sources must still be reachable at request time, not only at build time. Otherwise, those crawlers may get a 500 error.

Sitemap and robots

Next.js can generate sitemap.xml and robots.txt from code. File app/sitemap.ts:

TypeScript
import type { MetadataRoute } from 'next'
import { getPosts } from '@/lib/posts'

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = await getPosts()
  const latest = posts[0]?.updatedAt

  return [
    { url: 'https://example.com', lastModified: latest },
    { url: 'https://example.com/blog', lastModified: latest },
    ...posts.map((post) => ({
      url: `https://example.com/blog/${post.slug}`,
      lastModified: post.updatedAt,
    })),
  ]
}

Notice I use the date of the latest article instead of new Date(). Besides being more honest to search engines, it also sidesteps the current-time problem we covered in the caching section.

File app/robots.ts:

TypeScript
import type { MetadataRoute } from 'next'

export default function robots(): MetadataRoute.Robots {
  return {
    rules: [{ userAgent: '*', allow: '/', disallow: ['/dashboard', '/api'] }],
    sitemap: 'https://example.com/sitemap.xml',
  }
}

Structured data with JSON-LD

To help search engines and AI-powered answer engines understand the context of your pages, add structured data. In the Article component, build a JSON-LD object once you have the article data, then render it as a script tag at the start of <article>. The snippet looks like this:

TypeScript
const jsonLd = {
  '@context': 'https://schema.org',
  '@type': 'BlogPosting',
  headline: post.title,
  description: post.excerpt,
  datePublished: post.publishedAt,
  dateModified: post.updatedAt,
  image: post.cover,
  mainEntityOfPage: `https://example.com/blog/${post.slug}`,
}

return (
  <article>
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c') }}
    />
    <h1>{post.title}</h1>
    …
  </article>
)

That .replace(/</g, '\\u003c') isn't decoration. If an article's title or description contains </script>, without that escape the script tag can close early and open the door to XSS. Small thing, but details like this are what separate code that merely works from code that's ready for production.

Images and Fonts

next/image

The Image component from next/image takes care of a lot at once: resizing images for the screen, converting them to modern formats like WebP or AVIF, lazy loading, and keeping the layout from shifting while images load.

TypeScript
import Image from 'next/image'

<Image
  src={post.cover}
  alt={post.title}
  width={1200}
  height={630}
  sizes="(min-width: 768px) 720px, 100vw"
/>

The sizes prop gets skipped a lot, but it matters. Without it, the browser may download a huge image for a phone screen. For images from external domains, register their pattern in next.config.ts:

TypeScript
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    remotePatterns: [new URL('https://cdn.example.com/**')],
  },
}

export default nextConfig

Next.js 16 also changed a few defaults: the cache for optimized images is now 4 hours instead of 60 seconds, and the default quality is locked at 75. If you need a different quality, register it in images.qualities first.

next/font

We already used next/font/google in the root layout. The font is downloaded at build time and served from your own domain, so there's no request to Google when someone opens your site. Its fallback metrics are also adjusted automatically, so the text doesn't jump when the real font finishes loading. Two classic web font problems, solved with zero extra config.

Deployment: Vercel or Self-Hosting

Deploying to Vercel is the smoothest path. Connect your repository, push, done. Features like a distributed cache and Skew Protection work out of the box.

But Next.js can be fully self-hosted too, and since March 2026 the Next.js team has been getting more serious about supporting other platforms through Build Adapters and its collaboration with OpenNext. For a VPS or a container, turn on standalone output in next.config.ts:

TypeScript
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  output: 'standalone',
  cacheComponents: true,
  partialPrefetching: true,
}

export default nextConfig

This mode produces a .next/standalone folder containing a minimal Node.js server plus only the dependencies you actually use. It's much smaller than copying your entire node_modules. Here's the multi-stage Dockerfile I use as a starting point:

Dockerfile
FROM node:22-alpine AS deps
WORKDIR /app
RUN corepack enable
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile

FROM node:22-alpine AS build
WORKDIR /app
RUN corepack enable
ARG NEXT_SERVER_ACTIONS_ENCRYPTION_KEY
ENV NEXT_SERVER_ACTIONS_ENCRYPTION_KEY=$NEXT_SERVER_ACTIONS_ENCRYPTION_KEY
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN pnpm build

FROM node:22-alpine AS run
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
COPY --from=build --chown=node:node /app/public ./public
COPY --from=build --chown=node:node /app/.next/standalone ./
COPY --from=build --chown=node:node /app/.next/static ./.next/static
USER node
EXPOSE 3000
CMD ["node", "server.js"]

A few details that trip people up:

  • HOSTNAME=0.0.0.0 is required in a container. Without it, the server only listens on localhost inside the container and can't be reached from outside.
  • The public and .next/static folders aren't copied into standalone automatically. You have to copy them yourself, like above. Forget this step and the site runs, but every CSS file and image returns a 404.
  • --chown=node:node and USER node keep the app from running as root, while still letting Next.js write its cache to .next/cache.
  • The Server Actions encryption key comes in as an ARG in the build stage, just like in the story from the Server Actions section.

If you run more than one instance, remember that the default runtime cache lives in each instance's own memory. For apps that lean heavily on caching, consider a shared cache handler.

Finally, keep things updated. In December 2025, a critical vulnerability was found in the React Server Components protocol, tracked as CVE-2025-66478 on the Next.js side, which allowed remote code execution on the server. Apps that were slow to update were seriously exposed. Since 16.4, Next.js can automatically remind you when there's a security update relevant to the version you're running.

The Mistakes I See Most Often

Across the Next.js projects I've worked on and reviewed, the same mistakes tend to come up again and again:

  1. 'use client' placed too high. One small piece of state in a layout turns the whole app into a Client Component. Push the boundary down to the smallest component that actually needs interactivity.
  2. Server Components calling their own API routes. Call the data function directly. There's no need for an extra HTTP round trip.
  3. Sequential await for data that doesn't depend on each other. Use Promise.all, or better yet, split it into components with their own <Suspense>.
  4. Authorization only in the proxy. The proxy is for redirects and light checks. Real verification happens close to the data.
  5. Server Actions without validation. Every action is a public endpoint. Check the session, check permissions, validate input.
  6. Secrets in NEXT_PUBLIC_ variables. Anything with that prefix can be read by anyone who opens DevTools.
  7. Reading cookies() inside 'use cache'. Read it outside and pass the value in as an argument.
  8. Learning from old tutorials without checking the version. getServerSideProps, middleware.ts, single-argument revalidateTag, and synchronous params access are no longer the right way to do things in Next.js 16.

When Next.js Isn't the Best Choice

I don't want this article to sound like an ad. Next.js is a great tool, but it isn't for every situation.

  • An internal dashboard behind a login, with no SEO needs. Vite with React Router or TanStack Router is often simpler. There's no server to babysit, just static files.
  • A documentation or content site that's almost entirely static. Astro, for example, ships far less JavaScript by default and has a lighter mental model.
  • A team with no experience running Node.js servers. If you don't want to use Vercel and aren't ready to manage containers, the operational complexity is real.
  • An app that's almost entirely real-time and runs in the browser, like a collaborative editor or a game. The server rendering advantages don't get much use there.

Next.js shines brightest in apps that need SEO and fast first loads while also having dynamic, interactive parts. News sites, e-commerce, SaaS products with marketing pages, and blogs with community features are its natural habitat.

Now, if you're just getting started, my advice is not to try to master everything at once. Start with a single page. Try it this way: fetch data in a Server Component, add one <Suspense>, cache one function with 'use cache', then build one form with a Server Action. Something like an article list page with a small comment form, just like the example above. Once those four things feel natural, the rest is really just variations on the same patterns.

Thanks for reading all the way to the end. It was a long one, but I hope you now see Next.js as a whole instead of a pile of features.

Hafidz Nc

Fractional Head of Digital

Discussion