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.
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.
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.
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.
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
}
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.
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.
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.
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.
index.js
) that displays a list of users.getServerSideProps
to load the user data server-side from the JSONPlaceholder API.