Next.js getServerSideProps 返回 null 导致页面空白
FreeGuideOnline
最新
2026-07-05
ts // 1. 正常返回页面 props { props: { data } }
// 2. 重定向 { redirect: { destination: '/login', permanent: false } }
// 3. 返回 404 页面 { notFound: true }
**任何不符合这三种结构的返回值都会导致渲染异常,其中返回 `null` 是最常见的陷阱。**
### 为什么 null 会触发空白页面?
当你在 `getServerSideProps` 中这样写:
```js
export async function getServerSideProps() {
const data = await fetchData();
if (!data) {
return null; // ❌ 错误
}
return { props: { data } };
}
Next.js 内部会接收到你返回的 null,并尝试按照约定去解析它。由于 null 不是一个合法对象,框架无法判断它属于 props、redirect 还是 notFound,因此会直接终止渲染流程,导致组件根本不会被挂载,最终浏览器呈现一片空白。更麻烦的是,控制台往往没有任何报错提示,让新手抓狂。
正确的处理方式:永远返回合法结构
下面我们针对常见的三种数据处理场景,给出对应的正确写法。
场景一:数据存在,正常渲染页面
export async function getServerSideProps() {
const data = await fetchData();
// 数据存在,直接返回 props
return {
props: { data },
};
}
场景二:数据为空或不存在时,显示 404 页面
export async function getServerSideProps(context) {
const { id } = context.params;
const data = await fetchItem(id);
if (!data) {
return {
notFound: true, // ✅ 显示 Next.js 内置 404 页面
};
}
return {
props: { data },
};
}
使用 notFound: true 后,Next.js 会自动渲染 pages/404.js 或默认的 404 界面,并且 HTTP 状态码也会正确设置为 404,对 SEO 十分友好。
场景三:权限校验失败或需要登录,执行重定向
export async function getServerSideProps(context) {
const session = await getSession(context.req);
if (!session) {
return {
redirect: {
destination: '/login',
permanent: false,
},
};
}
return {
props: { user: session.user },
};
}
重定向会让浏览器立即跳转到指定地址,用户体验清晰合理。
错误修复实例:将 null 改为 notFound
错误代码:
export default function ProductPage({ product }) {
// 组件中直接使用 product 渲染
return <div>{product.name}</div>;
}
export async function getServerSideProps(context) {
const { id } = context.params;
const res = await fetch(`https://api.example.com/products/${id}`);
const product = await res.json();
if (product.error) {
return null; // 🔴 问题根源
}
return { props: { product } };
}
修复后的代码:
export async function getServerSideProps(context) {
const { id } = context.params;
const res = await fetch(`https://api.example.com/products/${id}`);
const product = await res.json();
if (product.error || !product.id) {
return {
notFound: true, // 🟢 清晰的 404 行为,不再空白
};
}
return {
props: { product },
};
}
页面不再白屏,用户会看到友好的 404 提示,开发体验大幅提升。
进阶:使用 try/catch 保护异步请求
当 fetch 本身失败时(如网络错误),你可能也需要返回 404 或重试提示。
export async function getServerSideProps(context) {
try {
const { id } = context.params;
const res = await fetch(`https://api.example.com/products/${id}`);
if (!res.ok) {
return { notFound: true };
}
const product = await res.json();
return { props: { product } };
} catch (error) {
console.error('Fetch failed', error);
return { notFound: true }; // 或显示通用错误页面
}
}