Step-by-Step Guide to Server-Side Render React with Rust
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 />); return `<!doctype html> <html> <head> <title>React + Rust = ❤️</title> <script type="module" crossorigin src="/index.js"></script> </head> <body> <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<'static, 'static>> = 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()) }
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!

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different 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.

Python 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.

JavaScript 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.

This 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

I 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

The 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.
