Episode 1 | next.js SSR fundamentals
Just recently I wrote about not using meteor any more as a "one size fits all" solution - not because meteor is bad - but because there's other cool stuff which will no doubt convince you by giving it a chance. In this short tutorial series we are going to use the next.js shiny thing in combination with firebase as the database layer and mobx as state manager. This is not a next.js, firebase promo tour :) I will certainly find things which are super annoying and I'll also report them (until now next.js css handling is irritating to use, but they are working on it).
Over the next few articles we'll recreate https://tagbag.today. The app consists of an individual input field which allows you to enter one single word or sentence per day. Originally, this was a hackathon project from a few months ago using create-react-app, mobx and firebase.
This article will cover the basics of ssr with mobx and next.js and not touch firebase at all - if this is boring stuff for you, you may enjoy the followup firebase-auth article.
Let's first initiate a new project and add all the dependencies we need.
npm install --save firstname.lastname@example.org mobx mobx-react firebase
npm install --save-dev babel-plugin-transform-decorators-legacy
Using beta.18 here as in beta.19/20 is a with mobx. I'll update this post as soon as the issues are resolved.
DecoratorsRoot-import: I tend to be confused by relative madness - babel-root-import basically allows you to write instead (where ~/is the root of your source code). : I like the decorators pattern - if you don't, just use the wrapper functions instead. The mobx documentation
- serve a useful initial DOM, so that e.g. twitter and facebook can display rich snippets of your website.
- performance - there are edge cases in which ssr can also slow you down, but we won't go into that
is pretty awesome so you'll figure out how to refactor the @ decorators :)
The babel plugins are optional, but I included them as they make things more readable.
Next.js automatically parses your .babelrc so let's add the file containing the plugins.
- The server initially generates the DOM and sends it down to the client.
- The client renders the DOM.
Last thing left is to add the next.js scripts in package.json so that we can easily start/build from command line.
"build": "next build",
"start": "next start"
Getting started With SSR
Server-side rendering is an important part of almost every js based web-application. There are two main goals we want to archive:
I won't go into it too deeply as there are already good articles on why and where to use SSR: just to name one
SSR basically works like this:
Just after that, the client generates the initial DOM itself and compares its hash to the servers one. To avoid unnecessary re-renders the server should generate the same DOM as the client. This means that the first render must be deterministic!