TL;DR: Check out Tuono for a framework-like experience that allows you to run React on a multithreaded Rust server. You can find more details below.
Access the complete project here.
Requirements
- Node.js (used just for building the project with vite)
- NPM (node package manager)
- Rustup (Rust language toolchain)
- Cargo (Rust package manager)
Getting started
For this example, we will use Vite.js to set up the project and compile the React source code.
npm create vite@latest react-rust -- --template react-ts
The initialized project is designed for client-side applications exclusively. In the following section, we will explore what is necessary to adapt it for full-stack bundling.
React setup
React requires two distinct builds tailored for different environments:
- The client-side build
- The server-side build
What distinguishes these two outputs?
The client build incorporates all the hydration logic, enabling React to connect seamlessly with the HTML generated by the server. In contrast, the server build is a more streamlined version focused solely on rendering HTML based on the props received from the server.
Now, let’s create a new file named ./src/server.tsx, which will serve as the entry point for the server build, and insert the following code:
import "fast-text-encoding"; // Mandatory for React18 import { renderToString } from "react-dom/server"; import App from "./App"; export const Server = () => { const app = renderToString(<app></app>); return ` <title>React + Rust = ❤️</title> <script type="module" crossorigin src="/index.js"></script> <div> <blockquote> <p>If you're working with React 18 or a newer version, it's essential to run npm install fast-text-encoding. This step is necessary because the Rust server lacks the Node.js objects and functions and the Web APIs. As a result, we need to provide a polyfill for TextEncoder, which is required by react-dom/server (in fact it is declared beforehand).</p> </blockquote> <p>We need to modify the vite.config.ts file to include the two outputs:<br> </p> <pre class="brush:php;toolbar:false">import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ build: { rollupOptions: { output: { format: "iife", dir: "dist/", }, }, }, ssr: { target: "webworker", noExternal: true, }, plugins: [react()], });
Next, we should add a new script in the package.json file.
-- "build": "tsc && vite build", ++ "build": "tsc && vite build && vite build --ssr src/server.tsx",
Prepare the Rust server
For this example, we will use axum, a web framework that works on top of tokio.
To get started, let's set up the Rust project by creating a Cargo.toml file in the main directory, containing the following details:
[package] name = "react-rust-ssr-example" version = "0.1.0" edition = "2021" [[bin]] name = "ssr" path = "src/server/server.rs" [dependencies] ssr_rs="0.7.0" tokio = { version = "1", features = ["full"] } axum = "0.7.4" tower-http = {version = "0.6.0", features = ["fs"]}
This is the Rust manifest - pretty similar to the JavaScript package.json file.
Next, we’ll set up a file named src/server/server.rs, which will serve as the entry point for launching the Rust server.
use axum::{response::Html, routing::get, Router}; use ssr_rs::Ssr; use std::cell::RefCell; use std::fs::read_to_string; use std::path::Path; use tower_http::services::ServeDir; thread_local! { static SSR: RefCell<ssr>> = RefCell::new( Ssr::from( read_to_string(Path::new("./dist/server.js").to_str().unwrap()).unwrap(), "" ).unwrap() ) } #[tokio::main] async fn main() { Ssr::create_platform(); // build our application with a single route let app = Router::new() .route("/", get(root)) .fallback_service(ServeDir::new("dist")); // run our app with hyper, listening globally on port 3000 let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); } async fn root() -> Html<string> { let result = SSR.with(|ssr| ssr.borrow_mut().render_to_string(None)); Html(result.unwrap()) } </string></ssr>
This is where the magic unfolds. At the start of the program, we kick things off by initializing the JavaScript V8 engine with Ssr::create_platform(); Next, we create a V8 context in each thread using thread_local!. Finally, we render the HTML with SSR.with(|ssr| ssr.borrow_mut().render_to_string(None)); and send it to the client when the route http://localhost:3000/ is requested.
Run the server
To start the server, simply compile the assets with Vite and then launch the Rust server.
npm run build && cargo run
? You are running a full-stack React application using a Rust server. Finally, React runs within a multithreaded server (you can find some benchmarks here).
Final words
Managing a full-stack React application is not easy with Node.js that plenty of tools have been built overtime to support it, and as you could see with Rust it is even harder.
Tuono is an experimental full-stack framework aimed at simplifying the development of high-performance Rust applications, with a strong focus on both usability and speed.
The above is the detailed content of Step-by-Step Guide to Server-Side Render React with Rust. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

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.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
