返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
Web前端

Notes on Next.js Route Segment Config Options

Next.js route segment config options? Is it really that simple? The official docs are pretty scattered, so I might as well organize them myself. Dynamic rendering or static? How should you set the caching strategy? Developers still have to figure it out themselves.

曦远 (DealiAxy)约 15 分钟
目录18 个章节

Introduction

Hello everyone, I'm Xiyuan.

I originally wanted to publish the starblog admin dashboard refactoring article I wrote last night

but when I opened the blog I realized I forgot to commit 😂

so I'll write a new one instead

I've been using Next.js a lot lately anyway

I noticed the first render after deployment was very slow, and only then realized the "warm-up" issue

Of course, that's a story for another time

This framework has a lot of official conventions

They're all in the official docs, just fairly scattered. This article mainly summarizes these conventions.

The Next.js framework updates quickly; when things differ, follow the official documentation.

Caching and Rendering

// 控制页面重新验证的时间间隔(秒)
export const revalidate = 60; // 60秒后重新验证
export const revalidate = 0;  // 禁用缓存
export const revalidate = false; // 永久缓存

// 控制页面的渲染模式
export const dynamic = 'auto';          // 默认,自动选择
export const dynamic = 'force-dynamic'; // 强制动态渲染
export const dynamic = 'force-static';  // 强制静态渲染
export const dynamic = 'error';         // 如果使用动态函数则报错

// 控制动态段的行为
export const dynamicParams = true;  // 允许动态参数(默认)
export const dynamicParams = false; // 不允许动态参数

Runtime Configuration

// 指定运行时环境
export const runtime = 'nodejs';    // Node.js 运行时(默认)
export const runtime = 'edge';      // Edge 运行时

// 设置最大执行时间(秒)
export const maxDuration = 30; // 最多执行30秒

Data Fetching

// 控制 fetch 请求的缓存行为
export const fetchCache = 'auto';           // 默认缓存行为
export const fetchCache = 'default-cache';  // 默认缓存
export const fetchCache = 'only-cache';     // 只使用缓存
export const fetchCache = 'force-cache';    // 强制缓存
export const fetchCache = 'default-no-store'; // 默认不缓存
export const fetchCache = 'only-no-store';  // 只允许不缓存
export const fetchCache = 'force-no-store'; // 强制不缓存

Metadata and SEO

Metadata

Dynamically generating metadata

import type { Metadata } from 'next'

export async function generateMetadata({ params }: { params: { slug: string } }): Promise<Metadata> {
  // 根据动态参数获取数据
  const post = await getPost(params.slug)
  
  return {
    title: post.title,
    description: post.description,
    openGraph: {
      title: post.title,
      description: post.description,
      images: [post.image],
    },
  }
}

Defining static metadata

// 静态元数据
export const metadata: Metadata = {
  title: 'My Page',
  description: 'This is my page description',
  keywords: ['next.js', 'react', 'typescript'],
  openGraph: {
    title: 'My Page',
    description: 'This is my page description',
  },
}

Use Cases

Static Metadata is suitable for:

  • Pages with fixed content (e.g. About Us, Contact Us)
  • Pages that don't need to change based on route parameters
  • Simple static pages

Dynamic Metadata is suitable for:

  • Blog post detail pages (get title and description based on article slug)
  • Product detail pages (get info based on product ID)
  • User profile pages (get info based on user ID)
  • Any page that needs to dynamically generate metadata based on route parameters or external data

Static Params

// 生成静态参数(用于动态路由)
export async function generateStaticParams() {
  return [
    { slug: 'post-1' },
    { slug: 'post-2' },
  ];
}

Common Combination Examples

Fully Static Page

export const dynamic = 'force-static';
export const revalidate = false;

Real-time Dynamic Page

export const dynamic = 'force-dynamic';
export const revalidate = 0;

Periodically Updated Page

export const revalidate = 3600; // 每小时更新一次

Edge Runtime Optimization

export const runtime = 'edge';
export const dynamic = 'force-dynamic';

API Route Configuration

// 在 API 路由中也可以使用
export const runtime = 'edge';
export const maxDuration = 10;
ConfigUse Cases
revalidate = 0Real-time data display, e.g. stock prices, chat apps
revalidate = 60Periodically updated content, e.g. news, blogs
dynamic = 'force-static'Fully static pages, e.g. About Us
dynamic = 'force-dynamic'Personalized content, e.g. user dashboards
runtime = 'edge'Global distribution that requires low latency
fetchCache = 'force-no-store'Sensitive data, caching not allowed

Notes

  1. Can only be used in page or layout files: these configs are only valid in page.tsx, layout.tsx, or route.ts files
  2. These config options can only be used in Server Component Pages, Layouts, or Route Handlers
  3. Must be named exports: must use the export const syntax
  4. Config values must be statically analyzable (e.g. revalidate = 600 is valid, but revalidate = 60 * 10 is not)
  5. Type safety: TypeScript will check the types of these configs
  6. Priority: child route configs override parent route configs

These config options let Next.js precisely control each page's rendering and caching behavior, and are one of the core features of the App Router architecture.

Official Documentation

Route Segment Config (route segment configuration)

  1. Dynamic Routes (dynamic routes)

  2. Data Fetching and Caching (data fetching and caching)

  3. Rendering (rendering)

_EOF_

Notes on Next.js Route Segment Config Options

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…