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.
目录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;
Recommended Use Cases
| Config | Use Cases |
|---|---|
| revalidate = 0 | Real-time data display, e.g. stock prices, chat apps |
| revalidate = 60 | Periodically 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
- Can only be used in page or layout files: these configs are only valid in page.tsx, layout.tsx, or route.ts files
- These config options can only be used in Server Component Pages, Layouts, or Route Handlers
- Must be named exports: must use the export const syntax
- Config values must be statically analyzable (e.g. revalidate = 600 is valid, but revalidate = 60 * 10 is not)
- Type safety: TypeScript will check the types of these configs
- 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)
- Latest version: https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config
- Next.js 14 version: https://nextjs.org/docs/14/app/api-reference/file-conventions/route-segment-config
Related Documentation Pages
-
Dynamic Routes (dynamic routes)
-
Data Fetching and Caching (data fetching and caching)
-
Rendering (rendering)
_EOF_
Notes on Next.js Route Segment Config Options
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
主流 nodejs 包管理器 pnpm vs bun vs npm vs yarn 简单横评
pnpm还真是会玩空间魔术?单项目里它领先优势就这么点?Node.js 20把npm喂肥了,现在谁还敢说npm是废物?这测试结果真是让人摸不着头脑。
2025-08-27 · Web前端 · 约 1 分钟
魔改editormd组件,优化ToC渲染效果
前言 我的StarBlog博客目前使用 editor.md 组件在前端渲染markdown文章,但这个组件自动生成的ToC(内容目录)不是很美观,我之前魔改过一个树形组件 BootStrap-TreeView,所以就想要用这个树形组件来展示ToC。 原本的效果是这样的 image-20221020112752560 我魔改完的效果 image-20221020112914518 先分析一波 首先看
2022-10-20 · Web前端 · 约 1 分钟
Vue2.x项目整合ExceptionLess监控
前言 一直以来我们都是用Sentry做项目监控,不过前段时间我们的Sentry坏掉了~~(我搞坏的)~~ 但监控又是很有必要的,在sentry修好之前,我想先寻找一个临时的替代方案,同时发现网上关于ExceptionLess的资料少得可怜,ExceptionLess官方的文档也不是很完善,翻了好久文档和源码,于是有了本文…… 关于ExceptionLess 写.NetCore的同学应该不会陌生,这
2022-03-23 · Web前端 · 约 1 分钟
使用微软官方的IE虚拟机测试上古网站
下载地址:https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/ 虚拟机默认密码:Passw0rd!
2021-12-18 · Web前端 · 约 1 分钟
讨论
共 0 条加载评论中…