27 Server-side rendering (SSR) in Next.js

Server-side rendering (SSR) is an important technique in Next.js that makes it possible to generate the content of a web page on the server before it is sent to the browser. This is in contrast to traditional single-page applications (SPAs), where rendering takes place exclusively in the client.

27.1 How SSR works in Next.js

With SSR, the server processes the request and sends the finished rendered page to the client as HTML. This process involves running React components on the server to generate the HTML.

27.1.1 Advantages of SSR

  1. SEO optimization: Since the content is already rendered on the server side, search engines can crawl and index the page more easily.

2 Faster initial load time: Users see the content faster because the HTML is already complete and does not have to be generated in the browser.

3 Better performance on slow devices: Since most of the rendering takes place on the server, the CPU load on the client device is reduced.

27.1.2 Implementation of SSR in Next.js

SSR is typically implemented in Next.js via the getServerSideProps function. This asynchronous function runs on every page request on the server and can retrieve data for rendering the page.

27.1.2.1 Example:

export async function getServerSideProps(context) {
  // Retrieve data from the server
  const data = await fetchData();
  return { props: { data } };
}

function MyPage({ data }) {
  // Render logic of the page
}

27.2 Dynamic data handling

SSR is particularly useful for pages that display dynamic data, such as user profiles or real-time information. Since getServerSideProps is called on every request, current data can be retrieved and rendered.

27.3 Differences to static rendering

In contrast to static rendering (SSG), where pages are generated at build time, SSR allows pages to be created in real time. This is ideal for content that changes frequently or is user-specific.

27.4 Attention to server load

An important aspect of SSR is server load. Since rendering processes take place on the server with every page request, high traffic can lead to an increased load on the server. Optimizations and caching strategies can help to minimize the load.

27.5 Exercise: Creating a simple Next.js app with server-side rendering (SSR)

27.5.1 Task

Develop a simple Next.js application that loads a list of users from an external API (e.g. https://jsonplaceholder.typicode.com/users) on the server side and displays them on a page.

27.5.1.1 Requirements

  1. Page structure: Create a main page (index.js) that displays a list of users.
  2. Data retrieval: Use getServerSideProps to load the user data server-side from the JSONPlaceholder API.
  3. Data display: Display the users in a simple list or table on the main page.
  4. Styling: Add basic CSS to make the list look clear.