How Server-Side Rendering Works in Next.js

itsjp

Jaydeep Pipaliya

Posted on August 28, 2024

How Server-Side Rendering Works in Next.js

SSR

Server-Side Rendering means that the HTML of the page is generated on the server for each request. This is useful for pages that show frequently updated data, or for pages that have content that changes on every request.

How it works:

  1. When a request comes in, Next.js runs your page's code on the server.
  2. It fetches any necessary data and renders the React components to HTML.
  3. The server sends the fully rendered HTML to the client.
  4. The client's browser displays the HTML immediately and then loads the JavaScript.
  5. Once the JavaScript loads, it "hydrates" the page, making it fully interactive.

Implementation:

To implement SSR in Next.js, you use the getServerSideProps function. This function runs on every request.



export async function getServerSideProps(context) {
// Fetch data from external API
const res = await fetch(https://api.example.com/data)
const data = await res.json()

// Pass data to the page via props
return { props: { data } }
}

function Page({ data }) {
return <div>{data.title}</div>
}

export default Page

Enter fullscreen mode Exit fullscreen mode




Advantages:

  • Always up-to-date content
  • Better SEO as search engines can crawl the full content
  • Faster initial page load, especially on slower devices

Disadvantages:

  • Slower Time to First Byte (TTFB) as the server needs to generate the content for each request
  • Higher server load

SSR is ideal for pages with frequently changing data or where the content depends on user-specific information (like a personalized dashboard).

💖 💪 🙅 🚩
itsjp
Jaydeep Pipaliya

Posted on August 28, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related