SSR (server-side-rendering)
Background
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.
Workflow
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.
Notes:
- When user visit the website,
Node web server
try to render component to HTML on the server side. - The
Node web server
will send request to the api backend to fetchdynamic content
- 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
Frontend
- 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).
Backend
Django
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.
Flask
For Flask dev, we might also need below packages.
FastAPI
Pros and Cons
Pros:
- Good performance (First Paint (FP) and First Contentful Paint (FCP))
- The web app supports SEO very well.
Cons:
- Can not benefit from some awesome Django, Flask features (templates, form, built-auth)