Let's first check why SSR is introduced and what problem it solves.
If you create web app with
SPA pattern, check the HTML source code, you will see something like this:
<html lang="en"> <head> <link href="/static/css/main.caf06914.chunk.css" rel="stylesheet"> </head> <body> <div id="root"></div> <script src="/static/js/2.20b865e0.chunk.js"></script> <script src="/static/js/main.ed646a45.chunk.js"></script> </body> </html>
We notice some problems here:
- The above
<div id="root"></div>is empty, the search engine can not understand what the page is about without running the JS.
- The browser need to run some JS code to build the DOM tree (might need to send some extra requests), which make the web page is a little slow to load.
Server-side rendering (SSR) is a popular technique for rendering a client-side single page application (SPA) on the server and then sending a fully rendered page to the client. This allows for dynamic components to be served as static HTML markup.
- When user visit the website,
Node web servertry to render component to HTML on the server side.
Node web serverwill send request to the api backend to fetch
- After that, the HTML will be returned to the browser.
- The browser will run JS and attach the event handlers to the existing DOM elements. This also called rehydration
- We can use create-next-app to create a Next.js application (React).
- We can use create-nuxt-app to create Nuxt.js application (Vue).
For Django dev, we might also need below packages.
- Django REST framework which will help build REST API.
- dj-rest-auth or djoser for auth API support.
- django-cors-headers will help solve Cross-Origin Resource Sharing (CORS) issue.
- graphene-django Integrate GraphQL into your Django project.
For Flask dev, we might also need below packages.
Pros and Cons
- Good performance (First Paint (FP) and First Contentful Paint (FCP))
- The web app supports SEO very well.
- Can not benefit from some awesome Django, Flask features (templates, form, built-auth)