Next.js 从零搭建服务端渲染应用
MrSmy Lv5

React 单页应用最大的问题是首屏:HTML 是空的,SEO 也拿不到内容。Next.js 用「按页面选择渲染方式」解决了这件事。2022 年用的是 pages 目录 + 数据获取函数那一套,现在回头看,它是理解后面 App Router 的基础。

初始化

1
2
3
npx create-next-app@12 my-site --typescript
cd my-site
npm run dev
1
2
3
4
5
6
7
8
9
pages
├── _app.tsx # 全局布局、Provider
├── _document.tsx # HTML 结构、字体、脚本
├── api
│ └── hello.ts # API 路由
├── index.tsx # 首页
└── posts
├── index.tsx
└── [slug].tsx # 动态路由

pages 下的文件路径就是路由路径,[slug].tsx 这种方括号是动态段,[...all].tsx 是捕获所有段。

四种渲染方式

方式 函数 生成时机 适用
CSR 无 浏览器 后台管理、强交互页面
SSG getStaticProps 构建时 内容不常变的页面
ISR getStaticProps + revalidate 构建时 + 后台增量 文章列表、商品页
SSR getServerSideProps 每次请求 强个性化、实时数据

同一个项目里可以混用,按页面选择。

SSG:构建时生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// pages/posts/index.tsx
import { GetStaticProps } from 'next'

interface Post {
slug: string
title: string
date: string
}

export const getStaticProps: GetStaticProps<{ posts: Post[] }> = async () => {
const posts = await fetch('https://api.example.com/posts').then(r => r.json())
return {
props: { posts },
revalidate: 60
}
}

export default function PostList({ posts }: { posts: Post[] }) {
return (
<ul>
{posts.map(p => (
<li key={p.slug}>
<a href={`/posts/${p.slug}`}>{p.title}</a>
</li>
))}
</ul>
)
}

revalidate: 60 就是 ISR:页面仍然是静态的,但每 60 秒内第一个请求会触发后台重新生成。它是”内容型站点性价比最高”的方案——用户拿到的是静态文件,内容又不会太旧。

注意 getStaticProps 里不能使用只在浏览器可用的 API,也不能依赖请求上下文。它的产物在构建时就被固化了。

动态路由 + SSG

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// pages/posts/[slug].tsx
import { GetStaticPaths, GetStaticProps } from 'next'

export const getStaticPaths: GetStaticPaths = async () => {
const posts = await fetch('https://api.example.com/posts').then(r => r.json())
return {
paths: posts.map((p: any) => ({ params: { slug: p.slug } })),
fallback: 'blocking'
}
}

export const getStaticProps: GetStaticProps = async ({ params }) => {
const post = await fetch(`https://api.example.com/posts/${params!.slug}`).then(r => r.json())
if (!post) return { notFound: true }
return { props: { post }, revalidate: 300 }
}

fallback 三个取值差别很大:

  • false:只生成 paths 里列出的页面,其他一律 404。文章少、全量可控时用
  • true:未生成的页面先返回一个骨架,浏览器端再拉数据。适合页面数量极多的情况
  • blocking:未生成的页面在服务端现场生成,用户等待首屏即可看到完整内容。对 SEO 最友好

我们用 blocking,代价是第一个访问新文章的请求会慢一点。

SSR:每次请求都渲染

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { GetServerSideProps } from 'next'

export const getServerSideProps: GetServerSideProps = async (ctx) => {
const token = ctx.req.cookies.token
if (!token) {
return { redirect: { destination: '/login', permanent: false } }
}

const user = await fetch('https://api.example.com/me', {
headers: { Authorization: `Bearer ${token}` }
}).then(r => r.json())

return { props: { user } }
}

getServerSideProps 能拿到 req/res,所以 cookie、header、鉴权重定向都能做。但它意味着每个请求都要跑一次 Node 渲染,QPS 高的时候成本很明显——能静态化的页面就别用 SSR。

API 路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// pages/api/posts.ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'GET') {
return res.status(405).json({ message: 'Method Not Allowed' })
}

try {
const posts = await fetch('https://api.example.com/posts').then(r => r.json())
res.setHeader('Cache-Control', 's-maxage=60, stale-while-revalidate=300')
res.status(200).json(posts)
} catch (e) {
res.status(500).json({ message: 'internal error' })
}
}

pages/api 下的文件跑在 Node 里,可以安全地放密钥、做代理。s-maxage 配合 stale-while-revalidate 是 CDN 缓存的标准写法。

图片与性能

1
2
3
4
5
6
7
8
9
import Image from 'next/image'

<Image
src="/cover.png"
alt="封面"
width={1200}
height={630}
priority
/>

next/image 会自动生成 srcset、按需转 WebP、懒加载。priority 只给首屏最大的那张图加,其他保持懒加载,否则 LCP 反而变差。

踩过的坑

1. getStaticProps 里用不了 window

构建时在 Node 环境执行,任何浏览器 API 都会报错。需要客户端逻辑的放到 useEffect 里。

2. _app.tsx 里拿不到 getStaticProps 的数据

页面级数据只在页面组件里,_app 拿不到。全局数据要么在 _app 里 useEffect 拉,要么用 getInitialProps(但会退化成每次请求渲染,慎用)。

3. 环境变量泄漏

1
2
NEXT_PUBLIC_API_URL=https://api.example.com   # 会打进客户端包
SECRET_KEY=xxx # 只在服务端可用

只有 NEXT_PUBLIC_ 前缀的才会暴露给浏览器。反过来,任何加了前缀的都不是秘密。

4. ISR 与数据库不一致

revalidate: 60 意味着最多 60 秒的旧数据。做”发布后立刻可见”的功能时,需要在发布流程里调 res.revalidate(path) 主动刷新,光靠时间不够。

小结

pages 这套模型的核心思路是:把”数据获取”从组件里拿出来,交给渲染层决定时机。它换来的是更好的首屏和 SEO,代价是”哪些代码跑在服务端、哪些跑在浏览器”需要时刻清楚。后面 App Router 用 Server Components 把这件事推得更彻底,但理解 getStaticProps / getServerSideProps 的区别,仍然是看懂 Next.js 的入口。

  • 本文标题:Next.js 从零搭建服务端渲染应用
  • 本文作者:MrSmy
  • 创建时间:2022-08-16 14:05:00
  • 本文链接:https://fengyang.live/2022/08/16/Next.js从零搭建服务端渲染应用/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!