/ssr-rs

Server side rendering on rust servers using the v8 engine for parse and evaluate the javascript code

Primary LanguageRustApache License 2.0Apache-2.0

🚀 Rust server side rendering

Valerioageno API codecov

The project aims to enable server side rendering on rust servers in the simplest and lightest way possible.

It use an embedded version of the v8 javascript engine (rusty_v8) to parse and evaluate a built bundle file and return a string with the rendered html.

Currently it works with Webpack bundler v4.44.2; check it out here a full project who use this crate.

Getting started

Add this to your Cargo.toml:

[dependencies]
ssr_rs = "0.2.3"

Example

The all logic is stored inside the render_to_string() function.

use ssr_rs::Ssr;
use std::fs::read_to_string;

fn main() {

    let source = read_to_string("./path/to/build.js").unwrap();

    let html = Ssr::render_to_string(&source, "entryPoint", None);
    
    assert_eq!(html, "<!doctype html><html>...</html>".to_string());
}

There are included examples with the most famous server frameworks and a default frontend react app made using npx create-react-app and the typescript --template flag. Check here the example ReactJS template.

Example with initial props

use ssr_rs::Ssr;
use std::fs::read_to_string;

fn main() {

    let props = r##"{
        "params": [
            "hello",
            "ciao",
            "こんにちは" 
        ]
    }"##;

    let source = read_to_string("./path/to/build.js").unwrap();

    let html = Ssr::render_to_string(&source, "entryPoint", Some(&props));
    
    assert_eq!(html, "<!doctype html><html>...</html>".to_string());
}

Contributing

Any helps or suggestions will be appreciated.

License

This project is licensed under the MIT License - see the LICENSE_MIT || LICENSE_APACHE file for more information.