Web Front-end
JS Tutorial
Explain in detail the issues related to implementing react server renderingExplain in detail the issues related to implementing react server rendering
This article mainly introduces the detailed implementation of react server rendering from scratch. Now I will share it with you and give you a reference.
Preface
When I was writing koa recently, I thought, if part of my code provides API and part of the code supports SSR, how should I write it? (If you don’t want to split it into two services)
And I have also used some server-side rendering in the projects I wrote recently, such as nuxt, and I have also worked on next projects. It is true that the development experience is very friendly, but friendly is still friendly. , how is it implemented specifically? Have you ever considered it?
Based on a truth-seeking and pragmatic attitude, I chose react as the research object (mainly because Vue has been written a bit too much, which is disgusting). Then I will simply write a react server-side rendering demo at the minimum cost.
Technology stack used
react 16 webpack3 koa2
Let’s see how it implements server-side rendering, here we go!
Why use server-side rendering
Advantages
It’s nothing more than two points
-
SEO Friendly
Speed up the first screen rendering and reduce the white screen time
Then the question is what is SEO
One sentence introduction is that most of the websites we make now are SPA websites. All pages and data come from ajax. When the search engine spider comes to collect the web pages, they find that they are all empty? So do you think the weight and effect of your website's inclusion are good or bad?
The core of our SEO optimization is also described in the following content:
The following is the key point!
Let the server return the HTML with content to us. If the event occurs, the browser will render it again for mounting.
Build the koa environment
New An ssr project, and initialize npm
mkdir ssr && cd ssr npm init
In the following code, we use import jsx and other syntaxes, which are not supported by the node environment, so we need to configure babel
Create a new one in the current project Files app.js and index.js, and then
babel's entrance, the index.js code is as follows
require('babel-core/register')() require('babel-polyfill') require('./app')
The entrance of our project, the app.js code is as follows
import Koa from 'koa'
const app = new Koa()
// response
app.use((ctx) => {
ctx.body = 'Hello Koa'
})
app.listen(3000)
console.log("系统启动,端口:3000")root Create a new .babelrc file in the directory
The content is:
{
"presets": ["react", "env"]
}Install the dependencies required above
npm install babel-core babel-polyfill babel-preset-env babel-preset-react nodemon --save-dev npm i koa --save
Configure the startup script
package.json
"scripts": {
"dev": "nodemon index.js",
}Here you run npm run dev and open localhost:3000
You will see hello Koa
Is it very simple to start a service
Install React
cnpm install react react-dom --save
Create a new app folder in the root directory, and create a new main.js in the folder
The main.js code is as follows
import React from 'react'
export default class Home extends React.Component {
render () {
return <p>hello world</p>
}
}Server.js before modification
import Koa from 'koa'
import React from 'react'
import { renderToString } from 'react-dom/server'
import App from './app/main'
const app = new Koa()
// response
app.use(ctx => {
let str = renderToString(<App />)
ctx.body = str
})
app.listen(3000)
console.log('系统启动,端口:8080')At this time, npm run dev
You will see hello world appear on the screen
Open chrome developer The tool checks our request:

Our simplest react component becomes str and passed in
Here we use a method:
renderToString - In fact, it is to render the component into a string
So far, we have not added events and other interactive behaviors to the component. Let us try it next
Modify main .js code
import React from 'react'
export default class Home extends React.Component {
render () {
return <p onClick={() => window.alert(123)}>hello world</p>
}
}Refresh our page again, hey, is it useless?
That’s because the backend can only render the component into a string of html. Event binding and other things need to be executed on the browser side
So how do we bind the event?
Then you will definitely guess that since the server renders a string of html, the way to mount the event is to re-render it once in the browser
Just do it Do
Configure webpack
Create a new webpack.config.js under the root directory
The following is the content of webpack.config.js:
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: {
main: './app/index.js'
},
output: {
filename: '[name].js',
path: path.join(__dirname, 'public'),
publicPath: '/'
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
loaders: [
{test: /\.jsx?$/,
loaders: ['babel-loader'],
}
]
}
}The above configuration sets the entry to the app/index.js file
Then we will create one
The following is the code of app/index.js:
import Demo from './main' import ReactDOM from 'react-dom' import React from 'react' ReactDOM.render(<Demo />, document.getElementById('root'))
Because browser rendering needs to mount the root component to a certain dom node, we set an entrance for our react code
There is a problem at this time, that is, the document object node environment is not If it doesn't exist, how to solve it?
does not exist? If it doesn’t exist, then I don’t need it. The core of SSR is to return specific HTML content in the requested URL. I don’t care about events or anything like that, so I just return the root component directly to renderToString
.
Let’s modify our service code to support server rendering
Add some dependencies
cnpm i --save koa-static koa-views ejs
koa-static: In the middle of processing static files File
koa-views: middleware for configuring templates
ejs: a template engine
Modify the code of server.js
import Koa from 'koa'
import React from 'react'
import { renderToString } from 'react-dom/server'
import views from 'koa-views'
import path from 'path'
import Demo from './app/main'
const app = new Koa()
// 将/public文件夹设置为静态路径
app.use(require('koa-static')(__dirname + '/public'))
// 将ejs设置为我们的模板引擎
app.use(views(path.resolve(__dirname, './views'), { map: { html: 'ejs' } }))
// response
app.use(async ctx => {
let str = renderToString(<Demo />)
await ctx.render('index', {
root: str
})
})
app.listen(3000)
console.log('系统启动,端口:8080')Create our rendering template below
Create a views folder
Create a new index.html in it:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <base href="/client" rel="external nofollow" > </head> <body> <p id="root"><%- root %></p> <script src="/main.js"></script> </body> </html>
You can put some variables in this html, such as this , which is where the renderToString result will be placed later.
/main.js is the code built by react
Let’s test our code directly
1. In package.json
新增:
"scripts": {
"dev": "nodemon index.js",
"build": "webpack"
},2. 运行 npm run build, 构建出我们的react代码
3. npm run dev
点击一下代码,是不是会 alert(123)
tada 撒花,恭喜你,一个最简单服务器渲染就已经完成
到这里核心的思想就都已经讲完了,总结来说就下面三点:
起一个node服务
把react 根组件 renderToString渲染成字符串一起返回前端
前端再重新render一次
原理就是这么简单
但是具体开发的时候还会有各种各样的需求,比如:
不可能我每次改完代码都重新构建看效果吧 => 需要 实时构建
create-react-app 都是热更新,你还要刷新是不是太蠢了 => 需要支持热更新
其他一些配套的周边,如: react-router, redux 或者mobx怎么支持呢 => 需要完善的生态
.etc
这些问题都是用完 官方脚手架之后就回不去了的,所以更多的配置可以参考下面的repo(是一个工具链完善的最小实现),欢迎提PR
GitHub - ws456999/koa-react-ssr-starter: to understand && to explain how react ssr works
目前你可以在里面找到 react + react-router + mobx + postcss + 热更新的配置,除了react-router的配置有些差别,其他都跟client端差别不大
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of Explain in detail the issues related to implementing react server rendering. For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft





