- Published on
 
Cache-Control 详解及在 Next.js / Express / Hono.js 中的最佳实践
- Authors
 
- Name
 - Shelton Ma
 
Cache-Control 是 HTTP 协议中的一个响应头,专门用于定义缓存策略.通过合理配置 Cache-Control,可以有效提升 Web 应用的性能, 包括:
- 减少服务器压力
 - 提升页面和 API 响应速度
 - 优化静态资源的缓存
 
1. Cache-Control 示例场景
| 场景 | 推荐配置 | 解释 | 
|---|---|---|
| 静态资源 (图片/字体/JS) | public, max-age=31536000, immutable | 1年有效期 + 文件名带哈希,内容不变时缓存可用 | 
| API 数据 | private, max-age=60, must-revalidate | 数据每 60 秒更新,过期后需重新验证 | 
| 敏感信息 (如 Token) | no-store | 完全禁用缓存,确保每次请求都获取最新数据 | 
| SEO 相关 HTML 页面 | public, s-maxage=3600 | CDN缓存 1 小时,提高静态页面加载速度 | 
2. 实现
1. Next.js
// pages/api/chat-history.ts
import type { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const chatHistory = await fetchChatHistory();
  // 缓存 5 分钟,并允许 CDN 缓存
  res.setHeader('Cache-Control', 'public, max-age=300, s-maxage=300');
  return res.status(200).json(chatHistory);
}
2. express.js
app.get('/api/chat-history', async (req, res) => {
  const chatHistory = await fetchChatHistory();
  // 设置缓存头部,允许代理和 CDN 缓存 60 秒
  res.setHeader('Cache-Control', 'public, max-age=60, s-maxage=60');
  res.json(chatHistory);
});
Hono.js
import { Hono } from 'hono';
const app = new Hono();
app.get('/chat-history', async (ctx) => {
  const chatHistory = await fetchChatHistory();
  ctx.header('Cache-Control', 'public, max-age=300, s-maxage=300');
  return ctx.json(chatHistory);
});
next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/(.*)',  // 所有静态资源
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, max-age=31536000, immutable'
          }
        ]
      }
    ];
  }
};