In a previous article I began talking about NextJS, which helps to streamline some aspects of web site development using React. In this article I want to talk about one of NextJS's most useful features: Server-Side Rendering (SSR).
As you probably know, search engines typically examine the content of your page before any Javascript on the page executes. If that Javascript is actually loading content (which is often what React, Vue, and Angular do), the search engine may not "see" that content, and therefore not properly index your page. Google has been known to have some ways around this, but it's hardly a sure thing.
Server-Side Rendering solves this problem. It basically instructs React (in this case) to grab all the necessary content from the server before the page is rendered to the browser. And because the content is pulled before the render, there's actually a modest performance boost.
But implementing SSR in React has never been a very straightforward process. NextJS helps to solve that.
Any NextJS page can implement SSR. Let's say your page skeleton looks like this:
If you need to enable SSR for that page, you add code as follows:
You'll see that we've added a function called getServerSideProps. Inside this function, you put any code that needs to run before the page renders, such as authentication, api calls, etc. You then pass the result of those calls to a props object, which is returned to the main HomePage function above.
Now, when you load your page, you can automatically hydrate it with whatever data you obtained from the server *before* the page finishes rendering. Search engines will now see all the page content and can index it properly.
Two important points:
NextJS provides two other functions for other SSR needs:
Because I tend to build sites requiring authentication, and which usually need real-time database queries, I tend to use getServerSideProps. But if you're building a less complex site, check out the other two methods for the most efficient SSR and page-load handling.