getStaticProps VS getServerSideProps in NextJS
NextJS provides the way to render page at the build time and at run time on the server. Rendering at the build time is known as Static Site Generation (SSG) and rendering at run time is known as Server Side Rendering (SSR)
When to use getStaticProps or getServerSideProps
getStaticProps:
- getStaticProps is used for
Static Site Generation
(SSG). - It is ideal for pages with content that does not change frequently.
- It generates HTML pages at
build
time and serves them from aCDN
. - SSG offers
faster
page loading speeds. - getStaticProps can be used to create blog sites where content does not change frequently.
- Example usage:
export async function getStaticProps(context) {
// props are passed to the component as props
return {
props: {},
};
}
getServerSideProps:
- getServerSideProps is used for
Server Side Rendering
(SSR). - It is ideal for pages with dynamic content that changes frequently.
- It will generates HTML pages in real-time on each request to the server.
- The page content is not pre-rendered at build time instead, it is generated dynamically when the user accesses the page.
- Typically it results in slower page loading speeds compared to SSG because the server has to process the request and generate the HTML on the fly.
- Example usage:
export async function getServerSideProps(context) {
// props are passed to the component as props
return {
props: {},
};
}
We can choose between SSG and SSR based on our specific use cases and requirements for performance, dynamic content, and user experience.