DEV Community

Jaydeep Pipaliya
Jaydeep Pipaliya

Posted on

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).

Top comments (0)