SSR and SSG
SSR (Server-side Rendering
)
getServerSideProps
The page HTML is generated on each request
- similar to
SSG
, exceptgetServerSideProps
is ran ad-hoc onevery request
instead ofbuild time
SSG (Static Site Generation
)
Page HTML is generated at build time
- page HTML is generated when you run
next build
- This HTML is then reused on each request
- Can be cached by CDN
- This HTML is then reused on each request
getStaticProps
In NextJS, SSG is accomplished by getStaticProps
- Next.js will pre-render a page that exports
getStaticProps
at build time using the props returned bygetStaticProps
- Never runs on client; only runs in server
- fetch this data on pre-render
- Next.js allows you to export an async function called
getStaticProps
from the same file - This function gets called at build time and lets you pass fetched data to the page's
props
on pre-render
- Next.js allows you to export an async function called
- fetch this data on pre-render
- Never runs on client; only runs in server
When to use getStaticProps
The data required to render the page is available at build time ahead of a user's request
- The data comes from headless CMS (
Content Management System
)- CMS is a back end-only web
content management system
- CMS is a back end-only web
Below example will fetch the data from api, then provide the fetched data as props
aliased to repo
to the component
import type { InferGetStaticPropsType, GetStaticProps } from 'next' type Repo = { name: string stargazers_count: number } export const getStaticProps = (async (context) => { const res = await fetch('https://api.github.com/repos/vercel/next.js') const repo = await res.json() return { props: { repo } } }) satisfies GetStaticProps<{ repo: Repo }> export default function Page({ repo, }: InferGetStaticPropsType<typeof getStaticProps>) { return repo.stargazers_count }
getStaticPaths
If a page has Dynamic Routes and uses getStaticProps
, it needs to define a list of paths to be statically generated
- When you export a function called
getStaticPaths
(Static Site Generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified bygetStaticPaths
Next.js will statically generate /posts/1
and /posts/2
during next build
using the page component in pages/posts/[id].js
// pages/posts/index.js export const getStaticPaths = (async () => { return { paths: [ { params: { id: '1' }}, { params: { id: '2' }}, ], fallback: ... } })