You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 14:如何在请求时生成HTML并实现原getServerSideProps功能?

在Next.js 14中替代getServerSideProps实现请求时生成HTML的SSR

方案一:App Router(官方推荐)

在Next.js 14的App Router中,所有组件默认都是Server Components,你可以直接在组件里写异步代码获取数据,这些代码会每次请求都在服务器端执行,动态生成HTML返回给客户端,完全替代getServerSideProps的作用。

示例代码:

// app/page.tsx
async function HomePage() {
  // 这段代码每次请求都会在服务器端运行
  const res = await fetch('https://api.example.com/data', { cache: 'no-store' });
  const data = await res.json();

  return (
    <div>
      <h1>动态请求内容</h1>
      <p>{data.content}</p>
    </div>
  );
}

export default HomePage;

关键细节:

  • 给fetch加上{ cache: 'no-store' }参数,确保每次请求都重新拉取数据,不会复用缓存结果
  • 组件内的异步逻辑会自动在服务器端处理,不用额外写特定方法

如果需要获取请求上下文(比如请求头、Cookies),可以用headers()和cookies()函数:

import { headers, cookies } from 'next/headers';

async function HomePage() {
  const headersList = headers();
  const cookieStore = cookies();
  const userAgent = headersList.get('user-agent');
  const theme = cookieStore.get('theme')?.value;

  const res = await fetch(`https://api.example.com/data?theme=${theme}`, { cache: 'no-store' });
  const data = await res.json();

  return (
    <div>
      <h1>基于请求上下文的动态内容</h1>
      <p>用户代理: {userAgent}</p>
      <p>当前主题: {theme}</p>
      <p>{data.content}</p>
    </div>
  );
}

方案二:Pages Router(兼容旧项目)

如果你还在使用Pages Router(Next.js 12及之前的目录结构),getServerSideProps在Next.js 14里依然可以正常使用,并没有被移除,直接按原来的写法就行:

// pages/index.tsx
export default function HomePage({ data, userAgent }) {
  return (
    <div>
      <h1>动态请求内容</h1>
      <p>用户代理: {userAgent}</p>
      <p>{data.content}</p>
    </div>
  );
}

export async function getServerSideProps(context) {
  // 每次请求都会在服务器端执行这段逻辑
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();
  const userAgent = context.req.headers['user-agent'];

  return {
    props: { data, userAgent } // 把数据传给页面组件
  };
}

补充说明

  • 如果是从Pages Router迁移到App Router,优先用Server Components的异步数据获取方式,这是官方主推的方向
  • 要是需要做交互逻辑的客户端组件,在组件顶部加'use client'指令,但客户端组件不能直接写异步数据获取,得通过Server Components传数据,或者用SWR、React Query这类客户端数据库

内容的提问来源于stack exchange,提问作者Aquib Mulla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 12:55:22