Chapter 3: Server-Side Rendering

Single Page Apps
19:50

SPA do all the work client-side, in particular the rendering. The client downloads a shell page and a JavaScript bundle which takes care of rendering.

Drawbacks

  • Slow first load
  • Multiple round trips
  • SEO
  • Accessibility
  • Doesn't work without JavaScript

Idea

JavaScript can also be run server-side. Why don't we run React there too to directly have HTML?

Client-Side vs Server-Side rendering
19:50

Client-Side rendering

The JavaScript code is executed by the browser (e.g. V8, Spider Monkey) to generate DOM nodes.

  • Better for UX
  • Better performance after the first render
  • Access to the DOM API

Server-Side rendering

The JavaScript code is executed by the server (e.g. Node) to generate HTML, which is then sent to the client.

  • Better for SEO
  • Better performance for the first render (closer to the data source for data fetching)
  • Better caching
  • Better for accessibility
  • No need to serve the libraries to the client
  • No multiple round trips
  • Works without JavaScript for the client

Introducing meta-frameworks
19:50

As JavaScript can be used on the client and on the server, React can run on Node, with the caveat that it does not have access to the DOM API. Instead, it returns an HTML string.

Idea

As much as possible, we should strive to offer both rendering strategies (CSR and SSR) and let the developer pick the right one. Client-side code should always have an SSR fallback.

For this course, we shall use Next.js, which is a meta-framework allowing you to write React code to be rendered on the client or the server.

File-Based routing
19:50

Next uses file-based routing.

Example

Layouts allow you to wrap your page into a component (e.g. to add a navbar). They can be put in app/[route]/layout.tsx. Layout apply to subroutes.

Remark

Next.js handles the routing on client if possible and fallsback to server-side routing.

React Server Components and Network Boundary
19:50

Definition (Server Component)

A server component in React is a component which will be transformed by React on the server into an HTML string.

  • It can contain backend code (database, etc.)
  • Can be asynchronous
  • It cannot use browser features (DOM API)
  • They cannot useState or useEffect

In Next.js, components are server components by default. Client components (i.e. what you have done so far) need 'use client' at the top of the file.

Remark

Client components cross the network boundary and can only have client components inside them

Set up your project
19:50

  • Run npx create-next-app@latest
  • Use TypeScript and ESLint
  • Use the App Router

Use the Next.js documentation.