Next.js
Static Generation
Automatically statically generated by Next.js
Pages without external data
function About() {
return <div>About</div>
}
export default About
Pages with external data
// TODO: Need to fetch `posts` (by calling some API endpoint)
// before this page can be pre-rendered.
function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
)
}
export default Blog
Pages with external data
function Blog({ posts }) {
// Render posts...
}
// This function gets called at build time & in development mode on every request
export async function getStaticProps() {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts')
const posts = await res.json()
// By returning { props: { posts } }, the Blog component
// will receive `posts` as a prop at build time
return {
props: {
posts,
},
}
}
export default Blog
getStaticProps
- Can only be used inside pages
- Request specific data (such as HTTP headers) is not available
When to use?
- Whenever possible
- "Can I pre-render this page ahead of user's request?"
When not to use?
- Page depends on the user's request e.g. profile page (example.com/my-profile)
- Page shows frequently updated data
- Page content changes on every request
Next.js static generation
By tume
Next.js static generation
- 77