Difference Between getStaticProps and getServerSideProps in Next.js

clock icon

Asked 1 year ago

message icon

1

eye icon

3

In Next.js, getStaticProps and getServerSideProps are two data-fetching methods used to pre-render pages. While both serve to fetch data before rendering a page, they differ significantly in when and how often the data is fetched and rendered. Understanding their differences is key to optimizing performance and user experience.

1 Answer

βœ… getStaticProps (For static pages β€” built once)

Think of it like this:

πŸ—οΈ β€œI want to build this page once, ahead of time, when I build my project β€” and then reuse it for every user.”

  • Runs at build time (when you run npm run build)
  • The page becomes a static HTML file
  • Faster for users β€” no server wait
  • Great for pages that don’t change often (e.g., blog post, about page)

Example use case: A blog page where the post content doesn't change often.


βœ… getServerSideProps (For dynamic pages β€” built on every request)

Think of it like this:

🌐 β€œI want to fetch fresh data every time a user visits the page.”

  • Runs on the server, every time someone visits the page
  • You always get the latest data
  • Slower than static, but always up to date
  • Good for things like user dashboards, live data, or personalized content

Example use case: A dashboard showing real-time user data or logged-in user's settings.


You don’t call them yourself. Next.js automatically calls them for you when:

  • A user visits a page that exports one of them
  • You define it like this inside a page component (not in a regular component):
1// pages/blog.js
2export async function getStaticProps() {
3 // Next.js calls this at build time
4 const res = await fetch('https://api.example.com/posts')
5 const posts = await res.json()
6 return {
7 props: {
8 posts,
9 },
10 }
11}
1// pages/blog.js
2export async function getStaticProps() {
3 // Next.js calls this at build time
4 const res = await fetch('https://api.example.com/posts')
5 const posts = await res.json()
6 return {
7 props: {
8 posts,
9 },
10 }
11}
1// pages/dashboard.js
2export async function getServerSideProps(context) {
3 // Next.js calls this on *every request*
4 const res = await fetch('https://api.example.com/dashboard')
5 const data = await res.json()
6 return {
7 props: {
8 data,
9 },
10 }
11}
1// pages/dashboard.js
2export async function getServerSideProps(context) {
3 // Next.js calls this on *every request*
4 const res = await fetch('https://api.example.com/dashboard')
5 const data = await res.json()
6 return {
7 props: {
8 data,
9 },
10 }
11}

1

Write your answer here

Top Questions