HTML / CSS

NextJs Server Rendered React App

My colleague Lewis Freiberg introduced me to Next.js during one of our weekly front-end meet-ups. I'd heard of it before, but hadn't taken it seriously. I...

14 Oct 2023

NextJs Server Rendered React App

My colleague Lewis Freiberg introduced me to Next.js during one of our weekly front-end meet-ups. I'd heard of it before, but hadn't taken it seriously. It was just another way to start a React app, like create-react-app.

I was wrong.

Why server rendering matters

A client-rendered React app ships an empty HTML page and a JavaScript bundle. The browser downloads the JS, executes it, then renders the UI. Until that's done, the user sees nothing. Search engines see nothing.

Next.js flips this. The server renders your React components into HTML and sends that to the browser. The user sees content immediately. The JavaScript loads in the background and "hydrates" the page, making it interactive.

Two wins from this:

  • Faster first paint. The browser renders HTML much faster than it can parse and execute JavaScript.
  • SEO. Search engine crawlers get real content instead of an empty <div id="root"></div>.

The trade-offs

Server rendering isn't free. Your server now does rendering work on every request (or at build time with static generation). This means more server resources and more complexity in your deployment.

You also lose the simplicity of a pure SPA. Some client-side libraries don't work on the server. You need to think about which code runs where. window doesn't exist on the server. Neither does localStorage.

When to use it

If your app needs SEO -- a marketing site, a blog, an e-commerce store -- server rendering is the right default. If you're building an internal dashboard that no search engine will ever see, a client-rendered SPA is simpler and just as effective.

Next.js has become my go-to for any new project that needs server rendering. The ecosystem, documentation, and community support are strong. If you're starting a React project today, it's worth considering.