Server-side rendering

Frontend web frameworks allow developers to create web apps in a high level language and component model. The web app is built into a static web site to be rendered in the browser. While many frontend web frameworks are based on JavaScript, such as React and Vue, Rust-based frameworks are also emerging as the Rust language gains traction among developers. Those web frameworks render the HTML DOM UI using the WebAssembly, which is compiled from Rust source code. They use wasm-bindgen to tie the Rust to the HTML DOM. While all of these frameworks send .wasm files to the browser to render the UI on the client-side, some provide the additional choice for Server-side rendering. That is to run the WebAssembly code and build the HTML DOM UI on the server, and stream the HTML content to the browser for faster performance and startup time on slow devices and networks.

If you are interested in JavaScript-based Jamstack and SSR frameworks, such as React, please checkout our JavaScript SSR chapter.

This article will explore how to render the web UI on the server using WasmEdge. We pick Percy as our framework because it is relatively mature in SSR and Hydration). Percy already provides an example for SSR. It’s highly recommended to read it first to understand how it works. The default SSR setup with Percy utilizes a native Rust web server. The Rust code is compiled to machine native code for the server. However, in order to host user applications on the server, we need a sandbox. While we could run native code inside a Linux container (Docker), a far more efficient (and safer) approach is to run the compiled code in a WebAssembly VM on the server, especially considerring the rendering code is already compiled into WebAssembly.

Now, let’s go through the steps to run a Percy SSR service in a WasmEdge server.

Assuming we are in the examples/isomorphic directory, make a new crate beside the existing server.

cargo new server-wasmedge

You’ll receive a warning to let you put the new crate into the workspace, so insert below into members of [workspace]. The file is ../../Cargo.toml.

"examples/isomorphic/server-wasmedge"

With the file open, put these two lines in the bottom:

[patch.crates-io] wasm-bindgen = { git = "https://github.com/KernelErr/wasm-bindgen.git", branch = "wasi-compat" }

Why do we need a forked wasm-bindgen? That is because wasm-bindgen is the required glue between Rust and HTML in the browser. On the server, however, we need to build the Rust code to the wasm32-wasi target, which is incompatible with wasm-bindgen. Our forked wasm-bindgen has conditional configs that removes browser-specific code in the generated .wasm file for the wasm32-wasi target.

Then replace the crate’s Cargo.toml with following content.

[package] name = "isomorphic-server-wasmedge" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] wasmedge_wasi_socket = "0" querystring = "1.1.0" parsed = { version = "0.3", features = ["http"] } anyhow = "1" serde = { version = "1.0", features = ["derive"] } isomorphic-app = { path = "../app" }

The wasmedge_wasi_socket crate is the socket API of WasmEdge. This project is under development. Next copy the index.html file into the crate’s root.

cp server/src/index.html server-wasmedge/src/

Then let’s create some Rust code to start a web service in WasmEdge! The main.rs program listens to the request and sends the response via the stream.

  1. use std::io::Write;
  2. use wasmedge_wasi_socket::{Shutdown, TcpListener};
  3. mod handler;
  4. mod mime;
  5. mod response;
  6. fn main() {
  7. let server = TcpListener::bind("127.0.0.1:3000", false).unwrap();
  8. println!("Server listening on 127.0.0.1:3000");
  9. // Simple single thread HTTP server
  10. // For server with Pool support, see https://github.com/second-state/wasmedge_wasi_socket/tree/main/examples/poll_http_server
  11. loop {
  12. let (mut stream, addr) = server.accept(0).unwrap();
  13. println!("Accepted connection from {}", addr);
  14. match handler::handle_req(&mut stream, addr) {
  15. Ok((res, binary)) => {
  16. let res: String = res.into();
  17. let bytes = res.as_bytes();
  18. stream.write_all(bytes).unwrap();
  19. if let Some(binary) = binary {
  20. stream.write_all(&binary).unwrap();
  21. }
  22. }
  23. Err(e) => {
  24. println!("Error: {:?}", e);
  25. }
  26. };
  27. stream.shutdown(Shutdown::Both).unwrap();
  28. }
  29. }

The handler.rs parses the received data to the path and query objects and return the corresponding response.

  1. #![allow(unused)]
  2. fn main() {
  3. use crate::response;
  4. use anyhow::Result;
  5. use parsed::http::Response;
  6. use std::io::Read;
  7. use wasmedge_wasi_socket::{SocketAddr, TcpStream};
  8. pub fn handle_req(stream: &mut TcpStream, addr: SocketAddr) -> Result<(Response, Option<Vec<u8>>)> {
  9. let mut buf = [0u8; 1024];
  10. let mut received_data: Vec<u8> = Vec::new();
  11. loop {
  12. let n = stream.read(&mut buf)?;
  13. received_data.extend_from_slice(&buf[..n]);
  14. if n < 1024 {
  15. break;
  16. }
  17. }
  18. let mut bs: parsed::stream::ByteStream = match String::from_utf8(received_data) {
  19. Ok(s) => s.into(),
  20. Err(_) => return Ok((response::bad_request(), None)),
  21. };
  22. let req = match parsed::http::parse_http_request(&mut bs) {
  23. Some(req) => req,
  24. None => return Ok((response::bad_request(), None)),
  25. };
  26. println!("{:?} request: {:?} {:?}", addr, req.method, req.path);
  27. let mut path_split = req.path.split("?");
  28. let path = path_split.next().unwrap_or("/");
  29. let query_str = path_split.next().unwrap_or("");
  30. let query = querystring::querify(&query_str);
  31. let mut init_count: Option<u32> = None;
  32. for (k, v) in query {
  33. if k.eq("init") {
  34. match v.parse::<u32>() {
  35. Ok(v) => init_count = Some(v),
  36. Err(_) => return Ok((response::bad_request(), None)),
  37. }
  38. }
  39. }
  40. let (res, binary) = if path.starts_with("/static") {
  41. response::file(&path)
  42. } else {
  43. // render page
  44. response::ssr(&path, init_count)
  45. }
  46. .unwrap_or_else(|_| response::internal_error());
  47. Ok((res, binary))
  48. }
  49. }

The response.rs program packs the response object for static assets and for server rendered content. For the latter, you could see that SSR happens at app.render().to_string(), the result string is put into HTML by replacing the placeholder text.

  1. #![allow(unused)]
  2. fn main() {
  3. use crate::mime::MimeType;
  4. use anyhow::Result;
  5. use parsed::http::{Header, Response};
  6. use std::fs::{read};
  7. use std::path::Path;
  8. use isomorphic_app::App;
  9. const HTML_PLACEHOLDER: &str = "#HTML_INSERTED_HERE_BY_SERVER#";
  10. const STATE_PLACEHOLDER: &str = "#INITIAL_STATE_JSON#";
  11. pub fn ssr(path: &str, init: Option<u32>) -> Result<(Response, Option<Vec<u8>>)> {
  12. let html = format!("{}", include_str!("./index.html"));
  13. let app = App::new(init.unwrap_or(1001), path.to_string());
  14. let state = app.store.borrow();
  15. let html = html.replace(HTML_PLACEHOLDER, &app.render().to_string());
  16. let html = html.replace(STATE_PLACEHOLDER, &state.to_json());
  17. Ok((Response {
  18. protocol: "HTTP/1.0".to_string(),
  19. code: 200,
  20. message: "OK".to_string(),
  21. headers: vec![
  22. Header {
  23. name: "content-type".to_string(),
  24. value: MimeType::from_ext("html").get(),
  25. },
  26. Header {
  27. name: "content-length".to_string(),
  28. value: html.len().to_string(),
  29. },
  30. ],
  31. content: html.into_bytes(),
  32. }, None))
  33. }
  34. /// Get raw file content
  35. pub fn file(path: &str) -> Result<(Response, Option<Vec<u8>>)> {
  36. let path = Path::new(&path);
  37. if path.exists() {
  38. let content_type: MimeType = match path.extension() {
  39. Some(ext) => MimeType::from_ext(ext.to_str().get_or_insert("")),
  40. None => MimeType::from_ext(""),
  41. };
  42. let content = read(path)?;
  43. Ok((Response {
  44. protocol: "HTTP/1.0".to_string(),
  45. code: 200,
  46. message: "OK".to_string(),
  47. headers: vec![
  48. Header {
  49. name: "content-type".to_string(),
  50. value: content_type.get(),
  51. },
  52. Header {
  53. name: "content-length".to_string(),
  54. value: content.len().to_string(),
  55. },
  56. ],
  57. content: vec![],
  58. }, Some(content)))
  59. } else {
  60. Ok((Response {
  61. protocol: "HTTP/1.0".to_string(),
  62. code: 404,
  63. message: "Not Found".to_string(),
  64. headers: vec![],
  65. content: vec![],
  66. }, None))
  67. }
  68. }
  69. /// Bad Request
  70. pub fn bad_request() -> Response {
  71. Response {
  72. protocol: "HTTP/1.0".to_string(),
  73. code: 400,
  74. message: "Bad Request".to_string(),
  75. headers: vec![],
  76. content: vec![],
  77. }
  78. }
  79. /// Internal Server Error
  80. pub fn internal_error() -> (Response, Option<Vec<u8>>) {
  81. (Response {
  82. protocol: "HTTP/1.0".to_owned(),
  83. code: 500,
  84. message: "Internal Server Error".to_owned(),
  85. headers: vec![],
  86. content: vec![],
  87. }, None)
  88. }
  89. }

The mime.rs program is a map for assets’ extension name and the Mime type.

  1. #![allow(unused)]
  2. fn main() {
  3. pub struct MimeType {
  4. pub r#type: String,
  5. }
  6. impl MimeType {
  7. pub fn new(r#type: &str) -> Self {
  8. MimeType {
  9. r#type: r#type.to_string(),
  10. }
  11. }
  12. pub fn from_ext(ext: &str) -> Self {
  13. match ext {
  14. "html" => MimeType::new("text/html"),
  15. "css" => MimeType::new("text/css"),
  16. "map" => MimeType::new("application/json"),
  17. "js" => MimeType::new("application/javascript"),
  18. "json" => MimeType::new("application/json"),
  19. "svg" => MimeType::new("image/svg+xml"),
  20. "wasm" => MimeType::new("application/wasm"),
  21. _ => MimeType::new("text/plain"),
  22. }
  23. }
  24. pub fn get(self) -> String {
  25. self.r#type
  26. }
  27. }
  28. }

That’s it! Now let’s build and run the web application. If you have tested the original example, you probably have already built the client WebAssembly.

cd client ./build-wasm.sh

Next, build and run the server.

cd ../server-wasmedge cargo build --target wasm32-wasi OUTPUT_CSS="$(pwd)/../client/build/app.css" wasmedge --dir /static:../client/build ../../../target/wasm32-wasi/debug/isomorphic-server-wasmedge.wasm

Navigate to http://127.0.0.1:3000 and you will see the web application in action.

Furthermore, you can place all the steps into a shell script ../start-wasmedge.sh.

#!/bin/bash cd $(dirname $0) cd ./client ./build-wasm.sh cd ../server-wasmedge OUTPUT_CSS="$(pwd)/../client/build/app.css" cargo run -p isomorphic-server-wasmedge

Add the following to the .cargo/config.toml file.

[build] target = "wasm32-wasi" [target.wasm32-wasi] runner = "wasmedge --dir /static:../client/build"

After that, a single CLI command ./start-wasmedge.sh would perform all the tasks to build and run the web application!

We forked the Percy repository and made a ready-to-build server-wasmedge example project for you. Happy coding!