Server-side Rendering
)getServerSideProps
The page HTML is generated on each request
SSG
, except getServerSideProps
is ran ad-hoc on every request
instead of build time
Static Site Generation
)Page HTML is generated at build time
next build
getStaticProps
In NextJS, SSG is accomplished by getStaticProps
getStaticProps
at build time using the props returned by getStaticProps
getStaticProps
from the same fileprops
on pre-rendergetStaticProps
The data required to render the page is available at build time ahead of a user's request
Content Management System
)
content management system
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
getStaticPaths
(Static Site Generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by getStaticPaths
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: ... } })