How does Server Side Rendering works in Next.js?

Viewed 1223

I am new to Next.js, coming from an express/create-react-app background, and can't wrap my head around how SSR works in Next.js.

With SSR on expressJs, we would click on a link, and the server will send the corresponding ejs/pug/html page matching the new route. The state on the client is lost, as expected.

But with Next.js, the state on the client remains, which is not how I expect SSR to behave. Maybe SSR with Next is more similar to fetching an api for data, like the flow I am imagining below?

  1. User visit a new page that requires SSR
  2. NextJs calls getServerSideProps to grab some data(from api/db) and populate props for the page component.
  3. Client's page component detects the new props and update itself(hydration?)

If someone can confirm or clarify would be appreciated.

Same page code for reference:

paged.js

import React from "react";
import axios from "axios";

const sendGetRequest = async () => {
  try {
    const resp = await axios.get("https://dog.ceo/api/breeds/image/random");
    return resp.data.message;
  } catch (err) {
    console.error(err);
  }
};

function Paged(props) {
  return (
    <div>
      <p>{props.dogstring}</p>
    </div>
  );
}

export async function getServerSideProps(context) {
  const dogstring = await sendGetRequest();
  return {
    props: {
      dogstring: dogstring,
    },
  };
}

export default Paged;
1 Answers

There are many posts available to compare SSR and CSR but I rather explain it in my words.

Let's assume there is a page (we didn't know about its implementation) for example www.sample.io

With opening the www.sample.io the client sends some HTTP/HTTPS requests (not API calls) to the webserver (usually nginx).

The webserver, serves that page so it sends the result to the client. This behavior is similar to SSR or CSR.

So, what are the differences?

In CSR, the webserver sends some source code to the client. The client (browser) parse them and draw HTML with the CSS styles and add the Javascript to the whole page.

In the SSR, the webserver sends a ready-to-show HTML with CSS and javascript. in other words, the server will parse the source code and draw the page then send the result to the client.

Other page functionalities like API calls, and users interaction like input forms, are handled by the Javascript without significant differences in SSR or CSR.

Related