0
0
NextJSframework~5 mins

How Next.js renders (server-first model)

Choose your learning style9 modes available
Introduction

Next.js renders pages first on the server to send ready HTML to the browser. This makes pages load faster and helps search engines understand your site better.

You want your website to load quickly for users on slow connections.
You want your site to be easy for search engines to find and rank.
You want to show content immediately without waiting for JavaScript to load.
You want to keep your page content secure before sending it to the browser.
You want to improve user experience by reducing blank screens during loading.
Syntax
NextJS
export default function Page() {
  return (
    <main>
      <h1>Hello from Server</h1>
    </main>
  )
}

// This component runs on the server first, then sends HTML to the browser.

Next.js uses React components that run on the server first by default.

You can add special functions like getServerSideProps to fetch data on the server before rendering.

Examples
A simple page component rendered on the server first.
NextJS
export default function Home() {
  return <h1>Welcome to Next.js!</h1>
}
This example fetches data on the server before rendering the page.
NextJS
export async function getServerSideProps() {
  return { props: { time: new Date().toISOString() } }
}

export default function TimePage({ time }) {
  return <p>Current server time: {time}</p>
}
This component runs in the browser after the server sends the HTML.
NextJS
'use client'

import { useState } from 'react'

export default function ClientComponent() {
  const [count, setCount] = useState(0)
  return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
}
Sample Program

This Next.js page uses getServerSideProps to prepare data on the server. The server sends the complete HTML with the message. The browser shows the message immediately without waiting for JavaScript.

NextJS
import React from 'react'

export async function getServerSideProps() {
  const message = 'Hello from the server!'
  return { props: { message } }
}

export default function Greeting({ message }) {
  return (
    <main>
      <h1>{message}</h1>
      <p>This page was rendered on the server first.</p>
    </main>
  )
}
OutputSuccess
Important Notes

Server-first rendering means the server creates the HTML before the browser sees it.

After the server sends HTML, React takes over in the browser to make the page interactive.

You can mix server rendering with client-side code for dynamic features.

Summary

Next.js renders pages on the server first to improve speed and SEO.

Use getServerSideProps to fetch data on the server before rendering.

The browser receives ready HTML and then adds interactivity with React.