Skip to content
ImagineWorld

Displaying Content in the Browser

node_idnode-book_rust-web-programming_chapter-07-displaying-content-in-the-browser
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleDisplaying Content in the Browser
pillar_membershipJ — architecture_design_craft
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 7 — Displaying Content in the Browser

Section titled “Chapter 7 — Displaying Content in the Browser”

We are now at the stage where we can build a web application that can manage a range of HTTP requests with different methods and data. This is useful, especially if we are building a server for microservices. However, we might also want non-programmers to interact with our application to use it. To enable non-programmers to use our application, we must create a graphical user interface.

It must be noted that this chapter does not contain much Rust. This is because other languages exist to render a graphical user interface. We will mainly use HTML, JavaScript (JS), and CSS. These tools are mature and widely used for frontend web development. Whilst I personally love Rust (otherwise I wouldn’t be writing a book on it), we must use the right tool for the right job. At the time of writing this book, we can build a frontend application in Rust using the Yew framework. However, being able to fuse more mature tools into our Rust technical stack is a more valuable skill.

This chapter will cover the following topics:

  • Building out a development setup
  • Serving the frontend from Rust
  • Connecting backend API endpoints to the frontend
  • Creating React components
  • Rendering multiple React components
  • Inserting styles with CSS

In the previous edition of this book, we created a React server using the npx command, meaning that the React application was created using an out-of-the-box configuration. We then served the frontend separately. In this edition, we still set up a development server for quick iteration, but we’ll embed all of the frontend application into the Rust binary and get the Rust server to directly serve the frontend itself, meaning that we only need one Rust binary for deployment, as opposed to running a Rust server and React server separately. In this chapter, we will be building our frontend application with esbuild without using out-of-the-box preconfigured tools. This will help you understand how the frontend is built and served. This will also empower you to come up with creative solutions and solve problems when they come up. We will also be building the frontend React application in TypeScript, as JavaScript still dominates the frontend and has the richest ecosystem. WASM frontend applications written in Rust still have big payloads compared to JavaScript payloads.

By the end of this chapter, you will know how frontend assets are served, and you will be able to utilize this knowledge to get Rust code to serve JS frontend applications. You will also be able to build a React application with different components and insert CSS into that application so the users can interact with it. To get the frontend talking to the backend, you will learn how to make API calls in the frontend to the backend.

You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.

This chapter’s code files are included in the downloadable code bundle.

You will also need esbuild to compile the React application, so you will need to install esbuild. You can do this using the following link: https://esbuild.github.io/getting-started/

Before we can start writing code that is executed in the browser to display our to-do items, we must set up our development environment. For our environment to support a React application that is built using esbuild, we need the following file layout:

Here, we can see that we have created an ingress and frontend directory. The ingress directory will house all the frontend code and will also have the main Rust server that will serve the frontend application and all backend endpoints. (The ingress directory is called ingress as the ingress of a system is where all the incoming traffic is handled.)

All our frontend code will be in the frontend directory, and all the assets that we will be serving after a frontend build will be in the frontend/public directory.

Why React?

At the time of writing this book, React is the dominant frontend framework. Multiple other frameworks have claimed that they are going to replace React, and while this is a possibility in the future, it has not happened yet. However, if you want to use another frontend framework, this chapter will still be useful. This chapter focuses on building and serving a React application. We will build the React application using esbuild, and we will serve the React app using two different methods, NGINX and the Rust server itself. If you want to use a different library, such as Angular or Vue, you can still build the frontend using esbuild, and you will still be able to serve the built frontend application using Rust or NGINX. The HTTP requests, CSS, and JSX will still be the same. However, you will have to read the specific API of the JavaScript framework that you want to use.

A good place for us to start is defining the parameters around the frontend build. This way, we will get to see where our entry point for the build is, the options for the build, and the output directory where the finished build is put.

To define the build, we must first import the following:

frontend/esbuild.js
const esbuild = require('esbuild');
const cssModulesPlugin = require('esbuild-css-modules-plugin');

The esbuild is used to define the build, and the cssModulePlugin is a plugin that enables esbuild to locally scope CSS class names to the JavaScript/TypeScript file, importing and using that CSS. This removes clashes of CSS names from other JavaScript/TypeScript files. This will help us scale our code as the project grows and gets more complex.

With these imports, we then define the build with the following code:

ingress/frontend/esbuild.js
esbuild.build({
plugins: [cssModulesPlugin()],
entryPoints: ['src/index.tsx'],
bundle: true,
outfile: 'public/bundle.js',
format: 'esm',
define: {
'process.env.NODE_ENV': '"production"',
},
}
minify: true,
sourcemap: true,
loader: {
'.js': 'jsx',
'.tsx': 'tsx',
'.ts': 'ts',
'.wasm': 'binary',
'.css': 'css'
},
}).catch(() => process.exit(1));

Our build parameters have the following outcomes:

  • plugins: Here, we add our CSS plugin, but we can also add other plugins if we want them.
  • entryPoints: Defines the entry point for the build. So, if any files are linked to the public/bundle.js file via imports in the code, these files will be included in the build.
  • bundle: Instructs esbuild to bundle all dependencies into a single output file. This makes it easier for us to deploy.
  • outfile: Where the bundle will be put once the build has finished.
  • format: Sets the module format of the output bundle to the ES module standard for JavaScript.
  • define: Replaces instances of process.env.NODE_ENV with “production” in the code for optimizations.
  • minify: Enables minification to cut out unnecessary symbols and whitespace, making the bundle file smaller.
  • sourcemap: Maps the bundled code back to source files, which is handy for debugging.
  • loader: Specifies the types of files that we load into the builder.

While this build config will enable us to build our React application with esbuild, we need some node modules and a node process to run esbuild. We can manually define our node dependencies and build processes in our frontend/package.json file with the following code (as opposed to using the npm init command):

frontend/package.json
{
"name": "es_react",
"version": "1.0.0",
"scripts": {
"build": "node esbuild.js",
"serve": "serve public"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
},
"devDependencies": {
"esbuild": "^0.24.0",
"esbuild-css-modules-plugin": "^3.1.0",
"serve": "^14.2.1"
}

Here, we can see that our application dependencies are just React-based and these dependencies are defined in the “dependencies” section. We have also defined the dependencies that we want for the build and serving in the “devDependencies” section.

We can see that we are using esbuild for the build. The build is achieved by running node against the esbuild.js file, which is the build config. Once the build is done, there will be a bundle.js in the public directory where our whole application is compiled to.

We have also defined the esbuild and esbuild-css-modules-plugin that we are using for the application build, and the serve dependency enables us to serve the React app when developing our application. These are in the “devDependencies” section because we do not need to add these modules to our bundle to be served to the client.

Before we move on to writing any TypeScript code, we must define our TypeScript build in the ts.config.json file as follows:

{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "CommonJS",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}

To avoid bloating the chapter, we will not break down the TypeScript config. This book is a book about Rust web programming, not a book on TypeScript.

If we tried to build our system now, it would break, as we have not defined our app in our entry point. Our app entry point is JavaScript that gets an HTML element by ID, to insert our React app into that HTML element. If we were using TypeScript, the TypeScript would be converted into JavaScript when the bundle is created, as JavaScript is the code that runs in the browser.

For our entry point, we can build the logic around injecting our React application into the HTML file that is served by the server with the following code:

frontend/src/index.tsx
import React from 'react';
import ReactDOM from "react-dom/client";
const App = () => {
return (
<div>
<h1>Hello World</h1>
</div>
);
};
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

For now, we are just injecting a

Hello World

into the element called root in the HTML file that is served. We will replace this placeholder later with our frontend application with to-do items.

Now we need to get our development environment to serve our application.

Connecting our development environment and application

Section titled “Connecting our development environment and application”

To do this, we first must have an HTML file that has an HTML element called root and loads our JavaScript bundle file that houses our React application. This is essentially an entry point for serving our application, so we can call this HTML file index.html. We will put this HTML file in our public directory because this is where the assets being served are stored for our server to access.

Our index.html file takes the following form:

<!DOCTYPE html>
<html>
<head>
<title>My React App</title>
</head>
<body>

We can configure the server to point to this index.html file with the server config file in the root directory of the following frontend:

frontend/serve.json
{
"rewrites": [
{ "source": "**", "destination": "./public/index.html" }
]
}

This means that we route all our requests to the server to the index.html file. Therefore, all requests are going to load the HTML file, which will download the bundled JavaScript file; this will then insert the React app into the root element of the index.html file. We can now run our server.

First, we must install the node modules for the building and serving of our application with the following command:

Terminal window
npm install

The node_modules directory will be created with all the packages needed for the building and serving of our application. We then build our application with the following command:

Terminal window
npm run build

After a stream of build logs, we should see the bundle.js file in the public directory. We can then serve our app with the following command:

Terminal window
npm run serve

This gives us the following printout:

Terminal window
> serve public
|
Serving!
- Local: http://localhost:3000
- Network: http://192.168.1.83:3000
- Copied local address to clipboard!

If we visit the localhost in the browser, we are greeted with the content shown in Figure 7.1.

Figure 7.1 – Our Basic React app viewed for the first time

Our logs in our console will show a printout along the same lines as the following:

HTTP 29/10/2024 17:32:54 ::1 GET / HTTP 29/10/2024 17:32:54 ::1 Returned 304 in 17 ms HTTP 29/10/2024 17:32:54 ::1 GET /bundle.js

Here, we can see that our server gets the index.html file with the HTTP 29/10/2024 17:32:54 ::1 GET /log, as we routed the GET request to the ./public/index.html file in our serve.json file earlier. The logs also show that we then get the bundle.js file. This makes sense as our index.html file loads the bundle.js file.

We can also inspect the network panel in our browser if we open developer tools in the browser. We do this by right-clicking on the web page in the browser and clicking Inspect. The Network tab in the developer tools will give us the log seen in Figure 7.2.

NameStatusTypeInitiatorSizeTimeWaterfall
localhost200documentOther561 B3 ms
bundle.js200script(index):846.1 kB11 ms

Figure 7.2 – Network logs of serving our React app

We can see that the HTML document is served, and then the JavaScript script is served. And here we have it! Our development environment is ready to build and serve our React application.

As an alternative approach, we could have used the Create React App tool to create a React application and serve it. However, there is a reason why you’re working through a book as opposed to speed-reading a tutorial online. Here, we are taking the time to go through how components in our stack work and interact with each other. This gives us more flexibility and the ability to build a system when there are multiple moving parts. For instance, we could reconfigure our serve.json file to have the following configuration:

{
"rewrites": [
{
"source": "/test",
"destination": "./public/test.html"
},
]

[figure outside: Figure 7.1, Figure 7.2]

As an alternative approach, we could have used the Create React App tool to create a React application and serve it. However, there is a reason why you’re working through a book as opposed to speed-reading a tutorial online. Here, we are taking the time to go through how components in our stack work and interact with each other. This gives us more flexibility and the ability to build a system when there are multiple moving parts. For instance, we could reconfigure our serve.json file to have the following configuration:

{
"rewrites": [
{
"source": "/test",
"destination": "./public/test.html"
},
{
"source": "**",
"destination": "./public/index.html"
}
]
}

With the preceding configuration, we can see that if the endpoint of the URL is test, we serve a different HTML file. This different HTML file could load a different JavaScript application using a different framework, or even load WebAssembly (WASM) assets. We can have multiple different bundles that are loaded by different HTML files. But we can even go further. Now that we know how the frontend is served, we do not have to use the serve node module; we can write our own servers that do this!

In the next section, we are going to apply what we have learned about bundling and serving frontend assets to embed those frontend assets into our Rust server binary in order for them to be served by our Rust server.

We now know that we can serve our React application if we can serve an HTML file that can point to the bundle.js file. Of course, we can do this using a Rust server. To achieve this, we can create an ingress workspace with the following directory layout:

Terminal window
├── Cargo.toml
├── README.md
├── frontend
│ ├── esbuild.js
│ ├── package-lock.json
│ ├── package.json
│ ├── public
│ │ ├── bundle.js
│ │ ├── bundle.js.map
│ │ └── index.html
│ │ │ serve.json
│ │ │ src
│ │ │ └── index.tsx
│ │ └── ts.config.json
│ └── ingress
├── Cargo.toml
└── src
└── main.rs

Here, the server in the ingress/src/main.rs file is going to point to our frontend/public folder to serve the assets. Now that we have our outline, we can serve our frontend by carrying out the following steps:

  1. Defining our frontend embedding dependencies
  2. Embedding the HTML file
  3. Embedding the React application
  4. Serving the embedded frontend

We can start by defining our dependencies needed to embed the frontend and serve it.

Defining our frontend embedding dependencies

Section titled “Defining our frontend embedding dependencies”

At this point, our Cargo.toml file in the root of our system now looks like the following:

Cargo.toml
[workspace]
resolver = "2"
members = [
"glue",

“ingress”, “nanoservices/to_do/core”, “nanoservices/to_do/dal”, “nanoservices/to_do/networking/actix_server” ]

By the end of the book, our ingress will accept all incoming requests and either serve frontend assets or backend endpoints. All our nanoservices will essentially be compiled into the ingress workspace. In this chapter, we will only focus on the serving of frontend assets. However, by Chapter 16, our entire system will be compiled into the ingress workspace.

Before we write any code for our ingress, our ingress/Cargo.toml file will need to have the following dependencies:

[package] name = “ingress” version = “0.1.0” edition = “2021”

[dependencies]
rust-embed = "8.3.0"
mime_guess = "2.0.4"
actix-web = "4.5.1"
tokio = {
version = "1.35.0",
features = ["macros", "rt-multi-thread"]
}

Here, we will be using the rust-embed crate to embed the frontend assets into our Rust binary on the build. We then use the mime_guess crate to work out what type of file we are serving when defining the file type, when returning it to the browser. This will help us serve CSS, images, WASM files, etc.

Other web frameworks for ingress

In the GitHub repository, the alternative-ingresses directory in the root of the system houses examples of ingresses written in Hyper, Axum, and Rocket. When there are changes in the approach, depending on the web framework, a high-level description of the differences will be covered in the book. The last dependency we need to define is our HTML file in the root of the ingress workspace, which has the following content:

<!DOCTYPE html>
<html>
<head>
<title>My To Do App</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./frontend/public/bundle.js">
</script>
</body>
</html>

We now have everything in place to serve a frontend application. Finally, we can write our main.rs file in our ingress workspace to embed our HTML.

First, we must import the following structs and traits:

ingress/src/main.rs
use actix_web::{
web, App, HttpServer, Responder, HttpResponse, HttpRequest
};
use rust_embed::RustEmbed;
use std::path::Path;

Now we embed our entry point - that is, the ingress/index.html file. We also need to return the HTML in an HTTP response with the following code:

ingress/src/main.rs
async fn index() -> HttpResponse {
HttpResponse::Ok().content_type("text/html")
.body(include_str!("../index.html"))
}

The include_str! macro embeds the contents of the file as a string, so that once the Rust code is compiled, we do not need to move the index.html file with the Rust binary; we only need the compiled Rust binary to serve the HTML. Our HTML file is now embedded in our Rust binary and ready to be served. We can now move on to embedding our React application. Embedding the React application

If we want to embed our React application, we must embed the ingress/frontend/public directory with the following code:

ingress/src/main.rs
#[derive(RustEmbed)]
#[folder = "../frontend/public"]
struct FrontendAssets;

With this, we can access files from the frontend/public directory via the FrontendAssets struct, as our frontend assets are now embedded into the Rust binary.

The serve_frontend_asset is going to be called by a catch-all function that is going to be connected to the server. Because we do not have any async calls in the serve_frontend_asset function, the serve_frontend_asset does not need to be async.

Now that we have embedded our frontend assets, we can then serve these assets.

Serving the embedded frontend

To serve a frontend asset, we get the path to the frontend asset and load the data, returning it with the following code:

ingress/src/main.rs
fn serve_frontend_asset(path: String) -> HttpResponse {
let file = match Path::new(&path).file_name() {
Some(file) => file.to_str().unwrap(),
None => return HttpResponse::BadRequest()
}
match FrontendAssets::get(file) {
Some(content) => HttpResponse::Ok()
.content_type(mime_guess::from_path(&file)
.first_or_octet_stream().as_ref())
.append_header(
("Cache-Control", "public, max-age=604800")
)
.body(content.data),
None => HttpResponse::NotFound().body("404 Not Found")
}
}

When it comes to getting a file from our FrontendAssets struct, we do not need a full path; instead, we only need the path from the ../frontend/public path. Because of this, we trim the path of the request, as our HTML file loads the bundle with the /frontend/public/bundle.js path. So, when our embedded HTML file makes the request for the bundle, we will trim the path to bundle.js by just getting the file_name of the path.

We then see if the file has been embedded into the FrontendAssets struct. If the file is not present, we return a not found response. If there is a file, we use the mime_guess crate to insert the data type into the header of the response. We also insert a Cache-Control parameter into the header. The max-age is calculated in seconds, so our assets will be cached in the browser for a week, which is the standard timeframe for caching. Finally, we insert the data of the file in the body of the HTTP response, and there we have it, our embedded frontend assets can be extracted and served to the browser.

When editing the frontend application, we must remember that the application is cached in the browser. So once the edit is done, we restart the server, and then in the browser, right-click inside the pane and select Inspect. You can then right-click on the refresh button and select Empty cache hard reload to ensure that you load the updated frontend that has your edits; otherwise, you will not see the changes in your browser.

We could just wrap the serve_frontend_asset function in an async function that accepts a request and returns an HTTP response. However, we will want to serve frontend assets no matter what the URL request is and serve backend API endpoints. This means that we have a function that is executed when all other endpoints are not hit. This is essentially a catch-all.

Our function takes the following signature:

ingress/src/main.rs
async fn catch_all(req: HttpRequest) -> impl Responder {
...
index().await
}

For the first check in our catch function, if the request has /api/ in the URL, then we return a not found, because this request was clearly intended for a backend endpoint. If the request has hit the catch function, this means that the request has not matched with any of the backend endpoints. This check is defined with the following code:

// File: ingress/src/main.rs (function = catch_all)
if req.path().contains("/api/") {
return HttpResponse::NotFound().finish()
}

191

For our next check, we can serve the frontend asset if there is a /frontend/public path in the request with the following code:

// File: ingress/src/main.rs (function = catch_all)
if req.path().contains("frontend/public") {
return serve_frontend_asset(req.path().to_string())
}

Our next check is to inspect the file type with the following code:

// File: ingress/src/main.rs (function = catch_all)
let file_type = match mime_guess::from_path(&req.path())
.first_raw() {
Some(file_type) => file_type,
None => "text/html"
};

If there is no file type in the request, it might just be hitting the route or our URL; therefore, we know that we want the index.html. However, the request might request another file type. For instance, when adding assets like images, it is common to reference the image path relative to the bundle, meaning that /frontend/public path is not in the asset path. Therefore, if the file type is not an HTML file, we can serve the frontend asset with the following code:

// File: ingress/src/main.rs (function = catch_all)
if !file_type.contains("text/html") {
return serve_frontend_asset(req.path().to_string())
}

If the request passes all these checks, we can just serve the index.html file with index.await return, as shown in the initial signature of the catch_all function.

We are finally at the point of defining our server that has our catch_all function as the default service. We do this with the following code:

ingress/src/main.rs
#[tokio::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.default_service(web::route().to(catch_all))
})
.bind("0.0.0.0:8001")?
.run()
.await
}

Now, when we perform a cargo run command, we can access our React application through our Rust server using the URL 0.0.0.0:8001/something/else, as seen in Figure 7.3.

Not Secure 0.0.0.0:8001/something/else

Figure 7.3 – Our Basic React app view from our Rust server

We can see that even though our URL has /something/else/ at the end, our React application is served. We will let our React application handle the missing frontend endpoint.

If we make a backend call that our server does not support, we will get a not found response, as seen in Figure 7.4.

0.0.0.0:8001/api/else

This 0.0.0.0 page can’t be found

No web page was found for the web address: http://0.0.0.0:8001/api/else

HTTP ERROR 404

Figure 7.4 – A not found response to an API endpoint

Here, we can conclude that our Rust server is serving our frontend.

Other web frameworks serving embedded frontends

Section titled “Other web frameworks serving embedded frontends”

For the Axum, Hyper, and Rocket frameworks, the method of embedding the frontend into the Rust binary is the same as for the Actix example we covered. However, there are some slight changes in how we return the files for the frontend.

Here, our serve_frontend_asset function returns a Response, and we define the header and file just like we do for Actix Web. Our catch_all function has the following signature:

async fn catch_all(uri: axum::http::Uri) -> impl IntoResponse

[figure outside: Figure 7.3] [figure outside: Figure 7.4]

Our catch_all function is mounted to our server using the fallback as seen in the following code:

let app = Router::new()
.route("/", get(index))
.fallback(catch_all);

Rocket

Due to Rocket having a higher-level API with more abstractions, we can serve our frontend by implementing our own custom responder with the following code:

struct CustomResponder<'r> {
status: Status,
content_type: ContentType,
data: Cursor<Vec<u8>>,
data_len: usize,
_phantom: PhantomData<&'r ()>,
}
impl<'r> Responder<'r, 'static> for CustomResponder<'r> {
fn respond_to(self, _: &'r Request<'_>) -> Response::Result<'static> {
Response::build()
.status(self.status)
.header(self.content_type)
.sized_body(self.data_len, self.data)
.ok()
}
}

The PhantomData will enable the compiler to keep track of the lifetime. Our serve_frontend_asset and catch_all functions return the CustomResponder. We create the Cursor from the data file with the following code:

let content_type: ContentType = ContentType::from_extension(
file.split('.').last().unwrap_or("")
.unwrap_or(ContentType::Any);
let raw_data = content.data.to_vec();
let data_len = raw_data.len();
let data = Cursor::new(raw_data);

Our catch_all function is mounted to our server using the catcher! macro with the following code:

let rocket = rocket::custom(&config);
let rocket = rocket.mount("/", routes![index, serve_frontend_asset]);
let rocket = rocket.register("/", catchers![catch_all]);
rocket.launch().await?;

Hyper

Because Hyper is lower level, we do not need to implement many extra steps. Our serve_frontend_asset function returns a Response<Full>. This response is constructed using the following code:

let bytes = Bytes::from(content.data.to_vec());
return Response::builder()
.header("Content-Type", mime_type)
.header("Cache-Control", "public, max-age=604800")
.body(Full::new(bytes)).map_err(|e| NanoServiceError::new(
e.to_string(),
NanoServiceErrorStatus::Unknown
))

Because we are implementing our own handle function that manually matches the HTTP method and URL, after all the manual matches are exhausted, we can return the catch_all function with the following code:

let response: Result<Response<Full<Bytes>>, NanoServiceError> =
match (
req.method(), segments.as_slice()) {
...
_ => Ok(catch_all(path).await),
};

For the next section, we will connect the API endpoints for our to-do items to the frontend.

Connecting backend API endpoints to the frontend

Section titled “Connecting backend API endpoints to the frontend”

We are going to connect our frontend to our backend server via HTTP requests. This means that we must connect our to-do nanoservice to our ingress.

Before we can do this, we must add the following dependencies to our ingress Cargo.toml file with the following code:

ingress/Cargo.toml

[dependencies]

…

actix-cors = "0.7.0"
to_do_server = {
path = "../nanoservices/to_do/networking/actix_server",
package = "to-do-actix-server"
}

We will use actix-cors to allow cross-origin requests, enabling our application to accept requests from different domains. Right now, this will not be an issue as our frontend will be making requests from the localhost on the same computer as the server. However, when we deploy our application, the React application will be running on a user’s computer and their requests will come from their computer, not the same computer that our server is running on.

We have also been compiling our to-do nanoservice into our ingress binary. However, note that we assign an alias of our to-do-actix-server package to to_do_server. This is because we might have another nanoservice that has the networking layer called actix_server and we do not want clashes. We might also get errors in compiling our project at this point. It is likely that there is no nanoservices/to_do/networking/actix_server/src/lib.rs file. We need a lib.rs file to enable the to-do server to be a package. Inside the lib.rs file, we must make the API publicly accessible with the following code:

nanoservices/to_do/networking/actix_server/src/lib.rs
pub mod api;

We can now redefine our server in the main.rs file of the ingress workspace. First, we use the following:

ingress/src/main.rs
...
use to_do_server::api::views_factory as to_do_views_factory;
use actix_cors::Cors;

We can now attach the views factory and CORs to our server with the following code:

ingress/src/main.rs
#[tokio::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
let cors = Cors::default().allow_any_origin()
.allow_any_method()
.allow_any_header();
App::new()
.configure(to_do_views_factory)
.wrap(cors)
.default_service(web::route())
})
}
.to(catch_all))
})
.bind("0.0.0.0:8001")?
.run()
.await

This is it, our server is now ready to serve our to-do endpoints to anywhere in the world if we had our server running on a public server that others can make requests to.

For the Axum, Hyper, and Rocket frameworks there are slight differences in the way we define the CORs policy.

We need the following dependency for our CORs middleware:

tower-http = { version = "0.6.1", features = ["cors"] }

We then define the CORs and attach that middleware to the server with the following code:

let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
let app = Router::new()
.layer(cors)
.route("/", get(index))
.fallback(catch_all);

For CORs middleware we must create a struct and implement the Fairing trait. The Fairing trait in Rocket allows us to hook into various stages of a request’s lifecycle, such as when a request is received, when a response is being finalized, or when the application starts or stops. By implementing Fairing, we can modify responses to include the necessary CORS headers, ensuring that browsers allow cross-origin requests. Here’s how we can do it with the following code:

pub struct CORS;
#[rocket::async_trait]
impl Fairing for CORS {
fn info(&self) -> Info {
Info {
name: "Add CORS headers to responses",
kind: Kind::Response
}
async fn on_response<'r>(
&self, _request: &'r Request<'_,
response: &mut Response<'r>
) {
response.set_header(Header::new(
"Access-Control-Allow-Origin", "*"
));
response.set_header(Header::new(
"Access-Control-Allow-Methods",
"POST, GET, PATCH, OPTIONS"
));
response.set_header(
Header::new(
"Access-Control-Allow-Headers",
"*"
)
);
response.set_header(
Header::new(
"Access-Control-Allow-Credentials",
"true"
)
);
}

As we can see, we are allowing all origins and methods. We can then attach the CORs middleware to the server with the following code:

let rocket = rocket::custom(&config);
let rocket = rocket.mount("/", routes![index, serve_frontend_asset]);
let rocket = rocket.register("/", catchers![catch_all]);
let rocket = rocket.attach(CORS);
rocket.launch().await?;

Hyper Because Hyper is lower level, all methods and origins are allowed, as we have not written any code to block any origins or methods. While our server is now ready to serve our to-do endpoints anywhere in the world, if we had it running on a public server, there are a couple of moving parts. For instance, you must build the frontend before embedding it. If you make a change to the frontend, there is a risk that you can rebuild your server without rebuilding the frontend. This can lead to time wasted trying to figure out why your changes are not showing. We can automate this with the following bash script for running a server in the scripts directory of the ingress:

#!/usr/bin/env bash

# navigate to directory
SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
cd $SCRIPTPATH
Terminal window
cd ../..
cd frontend
npm install
npm run build
cd ../ingress
cargo clean
cargo run

We are now less likely to miss a step in our server build process, saving us from confusion. We have added a lot of moving parts now, so it is a good idea to run the script and see if the server compiles and runs.

Note that this script will only work on computers where Rust and Node are installed. In Chapter 16, we containerize the server in Docker and deploy the containerized server on AWS.

We can now move on to the frontend, which has the following new files and directories:

…
src
:—:—

We can see that the API file structure follows the same layout at the core and networking layer. This is so our entire system is consistent, and you do not have to memorize three different structures for the core, networking, and frontend. Now that we have our project structure, we can implement our HTTP request using the following steps:

  1. Defining our interfaces
  2. Defining our API utils
  3. Defining our get API call
  4. Integrating our get API call in our main app
  5. Building out the rest of the API calls

However, before we write any code, we need the axios package to make HTTP requests. Our frontend package.json file dependencies should look like the following:

frontend/package.json
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"axios": "^1.6.8"
}

We could also install the axios package by running the npm install axios command. We now have everything we need to define our interfaces.

We define our interfaces through the following code:

frontend/src/interfaces/toDoItems.ts
export enum TaskStatus {
PENDING = 'PENDING',
DONE = 'DONE'
}
export interface ToDoItem {
title: string;
status: TaskStatus;
}
export interface ToDoItems {
pending: ToDoItem[];
done: ToDoItem[];
}

These interfaces are merely the structure of the data that we are passing between the server and the frontend. We can see that they are similar to the structs that we have been using in our Rust server. With these interfaces, we will be able to create items, update them, delete them, and get all items.

There is one more interface that we must construct, and this is the URL. We could define our URL as and when we need it; however, this makes it harder for us to maintain. If we have all our routes defined in one place, we can update mechanisms around constructing the URL, and we can easily keep track of all our URL endpoints. Seeing as our URL will be used when making API calls, we can define our URL interface in the api/url.ts file with the following outline:

frontend/src/api/url.ts
export class Url {
baseUrl: string;
create: string;
getAll: string;
update: string;
constructor() {
...
}
static getBaseUrl(): string {
...
}
deleteUrl(name: string): string {
return `${this.baseUrl}api/v1/delete/${name}`;
}
}

Here, we can see that our deleteUrl return value is slightly different from the other endpoints. This is because the name is passed into the delete URL. All the other URLs, which match the endpoints in the Rust server, are defined in the constructor with the following code:

frontend/src/api/url.ts
constructor() {
this.baseUrl = Url.getBaseUrl();
this.create = `${this.baseUrl}api/v1/create`;
this.getAll = `${this.baseUrl}api/v1/get/all`;
this.update = `${this.baseUrl}api/v1/update`;
}

Finally, we must define our base URL. Generally, we want our base URL to be the location of the browser. However, we must remember that we also have a development server for the frontend that runs on the localhost on port 3000, and our development server is on port 8001. Therefore, if our location is on the development server, we need to change the URL to point to the development Rust backend server with the following code:

frontend/src/api/url.ts
static getBaseUrl(): string {
let url = window.location.href;
if (url.includes("localhost:3000")) {
return "http://0.0.0.0:8001/";
}
return url;
}

We can now build the API utils that handle these interfaces.

The utils file is about abstracting some repetitive code that all other API calls will use so that we do not have to repeat ourselves.

Before we write our generic API call functions, we need to import the following:

frontend/src/api/utils.ts
import axios, {AxiosResponse} from "axios";

With this import, we can build our handle response function, which will have the following signature:

frontend/src/api/utils.ts
async function handleRequest<T, X>(
promise: Promise<AxiosResponse<X>>,
expectedResponse: number) {
let response: AxiosResponse<X>;
...
}

Here, we can see that our general understanding of async programming from Chapter 4 is helping us out. In this handle function, we accept a promise of a generic request. In our TypeScript code, we can handle our promises just like we would handle our futures in async Rust code. Inside the function, we await our API call promise and handle the outcome with the following code:

frontend/src/api/utils.ts
let response: AxiosResponse<X>;
try {
response = await promise;
}
} catch (error) {
return {
status: 500,
error: "Network Error",
data: JSON.stringify(error)
};
}

Like in Rust, the X is a generic type. We are using a generic type for the response because the response from the server could be different depending on the endpoint that we hit. For instance, later on in the book, we will have authentication sessions, and these API endpoints will not return to-do items.

If the HTTP request was not successful, we can conclude that this was the result of a network error. Therefore, we assign the status of 500, which is a network error. If the HTTP request fails, we want to handle the error as soon as possible. However, if our request succeeds, then we can assert that the response code is what we expect for the call, such as an OK, CREATED, or another response code, and return the data as the type we are expecting with the following code:

frontend/src/api/utils.ts
if (response.status === expectedResponse) {
return {
status: response.status,
data: response.data as X
};
} else {
return {
status: response.status,
error: `expected status ${expectedResponse} got
${response.status}`,
data: response.data as X
};
}

Now our handle request function is defined, we can lean on it to define a function that executes a post request. This post request will also have data in the body of the HTTP response. Our generic post request function takes the following form:

frontend/src/api/utils.ts
export async function postCall<T, X>(
url: string, body: T,
expectedResponse: number) {
let response = axios.post<X | string>(
url,
body,
);
{
headers: {
'Content-Type': 'application/json',
'token': "jwt"
},
validateStatus: () => true
};
return handleRequest(response, expectedResponse);
}

The validateStatus ensures that we resolve the promise for all response statuses. Note that we have the JWT in the header. Right now, this is a placeholder, but we will be reviewing the JWT in Chapter 10.

Finally, we need to define our get call function. Now is a good time to try and build this function yourself as it will be a slight variance to the post call function.

If you attempted to build the function yourself, it hopefully looks like the following code:

frontend/src/api/utils.ts
export async function getCall<X>(
url: string,
expectedResponse: number) {
let response = axios.get<X | string>(
url,
{
headers: {
'Content-Type': 'application/json',
'token': "jwt"
},
validateStatus: () => true
});
return handleRequest(response, expectedResponse);
}

With this, our utils for API calls are fully defined, and we are ready to use these utils to define our GET API call.

For our GET API call, our function takes the following form:

frontend/src/api/get.ts
import { ToDoItems } from "../interfaces/toDoItems";
import {getCall} from "./utils";
import { Url } from "./url";
export default async function getAll() {
let response = await getCall<ToDoItems>(
new Url().getAll,
200
);
return response;
}

This function makes an API call to the server to get all the to-do items. And that is it! We can see how implementing new API calls is going to be easy. However, before we implement more endpoints, we must check to see if our API calls work. To test this, we add our API GET call in our app.

Integrating our get API call in our main app

Section titled “Integrating our get API call in our main app”

To rewrite the App component, we must ensure that we have the following imported:

frontend/src/index.tsx
import React, { useState } from 'react';
import ReactDOM from "react-dom/client";
import getAll from './api/get';
import {ToDoItems} from "./interfaces/toDoItems";

We will cover what these imports are used for as and when we use them.

We define the following outline for our App component:

ingress/frontend/src/index.tsx
const App = () => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
React.useEffect(() => {
....
}, []);
return (
<div>
{error ? (
<div style={{ color: 'red' }}>Error: {error}</div>
) : data ? (
<div>Data loaded: {JSON.stringify(data)}</div>
) : (
<div>Loading...</div>
)}
</div>
);
};

Here, we have the useState, which handles the state for the App component. Our state is going to be the to-do items. We also render “Loading…” if our state is not loaded for the App component. If we have an error from the API call, we render the error. If we have loaded the data, we render the data instead.

Our React.useEffect fires once the App component has been loaded. This enables us to configure the state of the component, for instance, by fetching data and performing an action after the component is loaded.

In the React.useEffect, we make the GET call with the following code:

frontend/src/index.tsx
React.useEffect(() => {
const fetchData = async () => {
const response = await getAll();
if (response.error) {
setError(response.error);
} else {
setData(response.data);
}
};
fetchData();
}, []);

Here, we can see that we fire the setData function to render the items. If there is an error returned from the getAll function, we call the setError function to render the error.

We now have nearly everything we need to run our server with a frontend that serves the to-do items. There’s one more thing we need before we run the server, however, and that is to ensure that there is a tasks.json file in the root of the ingress workspace with the tasks. Once this is done, we run the ingress/scripts/run_server.sh script and visit the URL. This should give us the output seen in Figure 7.5.

{
"pending": [{"title":"writing","status":"PENDING"}],
"done": [{"title":"coding","status":"DONE"},{"title":"washing","status":"DONE"}]
}

And there we have it! We can see that our API call is working, and we can access our data from the server.

We now only need to build the create, delete, and update API calls. At this stage, this is a good time to try and build these functions yourself, as there is a bit of repetition with some slight variance when it comes to building the rest of the base API call functions for different call methods. This is a good time to test what you know about creating API calls.

[figure outside: Figure 7.5]

Building out the rest of the API calls

If you tried to create these functions yourself, hopefully, you will have taken an outline like the following approach. As we have covered all we need to know, the approach will merely spell out the code needed.

First, in the utils.rs file, we create a DELETE function with the following code:

frontend/src/api/utils.ts
export async function deleteCall<X>(
url: string,
expectedResponse: number) {
let response = axios.delete<X | string>(
url,
{
headers: {
'Content-Type': 'application/json',
'token': "jwt"
},
validateStatus: () => true
});
return handleRequest(response, expectedResponse);
}

In the same file, our PUT function is built with the following code:

frontend/src/api/utils.ts
export async function putCall<T, X>(
url: string, body: T, expectedResponse: number) {
let response = axios.put<X | string>(
url,
body,
{
headers: {
'Content-Type': 'application/json',
'token': "jwt"
},
validateStatus: () => true
});
return handleRequest(response, expectedResponse);
}

Also in the same file, our PATCH function is defined with the following code:

frontend/src/api/utils.ts
export async function patchCall<T, X>(
url: string, body: T,
expectedResponse: number) {
let response = axios.patch<X | string>(
url,
body,
{
headers: {
'Content-Type': 'application/json',
'token': "jwt"
},
validateStatus: () => true
});
return handleRequest(response, expectedResponse);
}

The create function then takes the following form:

frontend/src/api/create.ts
import { ToDoItem, ToDoItems, TaskStatus } from "../interfaces/toDoItems";
import { postCall } from "./utils";
import { Url } from "./url";
export async function createToDoItemCall(title: string) {
const toDoItem: ToDoItem = {
title: title,
status: TaskStatus.PENDING
};
return postCall<ToDoItem, ToDoItems>(
new Url().create,
toDoItem,
201
);
}

The update function is defined with the following code:

frontend/src/api/update.ts
import { ToDoItem, ToDoItems, TaskStatus } from "../interfaces/toDoItems";

import { patchCall } from ”./utils”; import { Url } from ”./url”;

Terminal window
export async function updateToDoItemCall(
name: string,
status: TaskStatus) {
const toDoItem: ToDoItem = {
title: name,
status: status
};
return patchCall<ToDoItem, ToDoItems>(
new Url().update,
toDoItem,
200
);
}

And finally, our delete to-do item function, which is essentially an interface for making a DELETE network call via the deleteCall function, takes the following form:

frontend/src/api/delete.ts
import { ToDoItems } from "../interfaces/toDoItems";
import { deleteCall } from "./utils";
import { Url } from "./url";
export async function deleteToDoItemCall(
name: string) {
return deleteCall<ToDoItems>(
new Url().deleteUrl(name),
200
);
}

Now we have defined all the API endpoints that we need. However, we need to interact with these API calls. We must create some to-do item and form components so that we can call these API functions with data.

With React, we can build JSX/TSX components that can be used as templates. These are essentially functions that render HTML with the aid of JavaScript or TypeScript. For instance, if we have a list of items, components enable us to loop through that list of items in JavaScript/TypeScript and render the HTML for those items. These components support internal state; updating the internal state can force a re-render of the component. We will explore the basic outline of the React component by building the create-to-do item component. This component takes an input for the title of the to-do item being created and keeps track of the state of the title. When the create button is clicked, the create component then makes an API call with the title to create the to-do item and then returns the updated state to the parent component. We can house our components in the frontend/src/components/directory. Let’s create that now. To build our create item form, we must carry out the following steps:

  1. Building a create item form
  2. Injecting our form component into our app
  3. Testing our create item form

With this, we can start creating the item form.

We can then start building our create component with the following imports and interface in our CreateItemForm.tsx file:

frontend/src/components/CreateItemForm.tsx
import React, { useState } from 'react';
import { createToDoItemCall } from "../api/create";
interface CreateToDoItemProps {
passBackResponse: (response: any) => void;
}
// The CreateToDoItemProps interface is what we are going to accept into the component when creating it. (Generally, what gets passed into the component when the component is being created is referred to as props.) In this case, we are passing a function that accepts the response of the create API call. We will see how the function works when we implement our components in the main application.

Now we can define the outline of our create component with the following code:

frontend/src/components/CreateItemForm.tsx
export const CreateToDoItem: React.FC<CreateToDoItemProps> = (
{ passBackResponse }
) => {
const [title, setTitle] = useState<string>("");
const handleTitleChange = (
e: React.ChangeEvent<HTMLInputElement>
) => {
setTitle(e.target.value);
};
const createItem = async () => {
...
};
}

Here, we can see that we initially define our state, which is just a string, as all we are doing is keeping track of the name of the to-do item that we are creating. We are assuming that all to-do items being created will be pending and not complete. We then define the function that updates the state of the to-do item title every time there is a change in the input HTML element where the user is inputting the title. This means that every time the user changes the input contents for the title of the to-do item, the entire React component has access to that data, and we can alter the component however we want. We then define our API call and the .tsx that the component is rendering.

For the create API call, our function takes the following form:

frontend/src/components/CreateItemForm.tsx
const createItem = async () => {
await createToDoItemCall(title).then(response => {
setTitle("");
passBackResponse(response);
});
};

Here, we can see that we pass the title state into the API call and then reset the state of the title. We then execute the function that was passed in via props so the main App component can access the response.

For our render statement, we have the following code:

frontend/src/components/CreateItemForm.tsx
return (
<div className="inputContainer">
<input type="text" id="name"
placeholder="create to do item"
value={title}
onChange={handleTitleChange}/>
<button className="actionButton"
id="create-button"
onClick={createItem}>Create</button>
</div>
);

Here, we render the title state in the input value so the user can see the state of the title. We then bind our listener to that input and bind the API call function to our button. We have referenced some CSS class names in the .tsx. Do not worry, even though we have not created them, the frontend will not crash if we do not have the CSS classes. We will define our CSS classes in the next section of this chapter. However, it is easier to reference the CSS classes now, when we are building the React components, to save us from bloating the chapter by going back and referencing the CSS classes in the components later. Now that our create item form is done, we should inject our create item form into our React application.

At this stage, it is a good idea to test if our component works. We can test our component by importing the component into the index of the frontend with the following code:

frontend/src/index.tsx
import { CreateToDoItem } from './components/CreateItemForm';

Inside the App component, a function that re-renders items to the browser is defined with the following code:

frontend/src/index.tsx
function reRenderItems(response: any) {
if (response.error) {
alert(JSON.stringify(response));
return;
}
else if (response.data) {
setData(response.data);
setError(null);
}
else {
setError("Unknown error");
}
}

Calling the setError function forces the App component to re-render with the updated data from the response. However, if there is an error, we get an alert instead.

We then insert the CreateItemForm component at the bottom of our return statement, giving our return statement the following outline:

frontend/src/index.tsx
return (
<div>
{error ? (
<div style={{ color: 'red' }}>Error: {error}</div>
) : data ? (
<div>Data loaded: {JSON.stringify(data)}</div>
)
</div>
);
}
) : (
<div>Loading...</div>
)
}
<CreateToDoItem passBackResponse={reRenderItems} />
</div>
);

Our create item is now ready to test.

Now we can create items. If we run the server, we get the form as seen in Figure 7.6:

Figure 7.6 – A create form for the to-do application

However, if we use the form, we will get the alert error as seen in Figure 7.7:

Figure 7.7 – Alert with API error

In the error response, we can see that we get the response that we expect with the created item, but the response returns a 200, which is an OK response as opposed to a 201, which is a CREATED response. This is a minor error that can be fixed with the following code:

src/basic_actions/create.rs
// File: nanoservices/to_do/networking/actix_server/
Ok(HttpResponse::Created().json(get_all_core().await?))

[figure outside: Figure 7.6] [figure outside: Figure 7.7]

However, because we coded some alerts based on unexpected API responses with a helpful error message and the data in the response, we have managed to diagnose the bug quickly and correct it. You may not want to give your users all the data, but logging these comprehensive responses somewhere when an anomaly is detected will save you time when trying to recreate the bug. The testing chapters will also cover how to detect these errors before deploying the application.

After correcting the response code to 201, you can run your server again, and the create form will work, resulting in the items being re-rendered. Now that our create form is working, we can move on to rendering multiple to-do items.

Our form is now ready to import and use, but before we add this form to our main application component, we should define our to-do item component in our ToDoItem.tsx file. We will need the following imports and interface:

frontend/src/components/ToDoItem.tsx
import React, {useEffect, useState} from 'react';
import {updateToDoItemCall} from "../api/update";
import { deleteToDoItemCall } from "../api/delete";
import {TaskStatus} from "../interfaces/toDoItems";
interface ToDoItemProps {
title: string;
status: string;
id: number;
passBackResponse: (response: any) => void;
}

Here, we can see that we are passing in the title, status, and ID of the to-do item. This makes sense as we want to render the item, and handle operations on the to-do item in the backend via making API calls in the to-do item component.

With this interface in mind, we now define our to-do item component in our ToDoItem.tsx file as follows:

frontend/src/components/ToDoItem.tsx
export const ToDoItem: React.FC<ToDoItemProps> = (
{ title, status, id, passBackResponse }) => {
const [itemTitle, setTitle] = useState<string>(title);
const [button, setButton] = useState<string>('');
useEffect(() => {
const processStatus = (status: string): string => {
return status === "PENDING" ? "edit" : "delete";
};
}, [title, status, id, passBackResponse]);
return itemTitle;
}
setButton(processStatus(status));
}, [status]);
const sendRequest = async (): void => {
...
};
return (
...
);
}

Here, we can see that we are using the useEffect to define what is going to be rendered in the button. If our status is pending, we can edit the to-do item to be complete, so the button has complete written on it. If the status is not pending, we then assume that the to-do item is complete, and the only thing that we want to do now is delete the to-do item, so the button renders “delete.”

Note that there is a [status] array in the useEffect function. This array is a dependencies array. This means that the useEffect function relies on the status before executing, which makes sense as we reference the status in the useEffect function.

Now that our state is defined, we can move on to the API call for editing the item. Here, we must check the type of button and make either the create or delete API depending on the button type. At this stage, you could try to build this API call yourself. There is some conditional logic that you must consider, and if you get this right, then you are truly comfortable making API calls to our backend. Remember to look at the to-do item component for a starting point.

If you attempted to build the API call yourself, hopefully, you have a structure like the following one:

frontend/src/components/ToDoItem.tsx
const sendRequest = async () => {
if (button === "edit") {
...
} else {
...
}
};

If our button is an edit button as opposed to a delete function, we have this API call:

frontend/src/components/ToDoItem.tsx
await updateToDoItemCall(
itemTitle,
TaskStatus.DONE
).then(
response => {
passBackResponse(response);
}
)

And then our delete button takes the following form:

frontend/src/components/ToDoItem.tsx
await deleteToDoItemCall(itemTitle).then(
response => {
passBackResponse(response.data);
}
)

And now our to-do item component will be able to make API calls to the backend by itself when the item edit or delete button is pressed!

Finally, we render the to-do item with the following return statement:

frontend/src/components/ToDoItem.tsx
return (
<div className="itemContainer" id={id}>
{itemTitle}
<button className="actionButton"
onClick={sendRequest}>
{button}
</button>
</div>
);

Here, we are merely rendering the button type and binding our API call to the button on click.

And there we have it, the components are finished, and all we need to do is place them in our application. In our index file for our application, we will now have the following imports:

frontend/src/index.tsx
import React, { useState } from 'react';
import ReactDOM from "react-dom/client";
import getAll from './api/get';
import {ToDoItems} from "./interfaces/toDoItems";
import { ToDoItem } from "./components/ToDoItem";
import { CreateToDoItem } from './components/CreateItemForm';

Now that we have our new components, we must handle them in our App component. We do this with the following code:

frontend/src/index.tsx
const App = () => {
...
if (error) {
return <div style={{ color: 'red' }}>Error: {error}</div>
}
else if (!data) {
return <div>Loading...</div>
}
else {
return (
...
);
}
};

We have now defined a reRenderItems function. This function just takes in the to-do items data, and updates the state, forcing a re-render of the application. The reRenderItems function is the function that we are going to pass to our create items form and to-do item components, so when these components perform an API backend call that is successful, they will pass the returned state of the to-do items back to our reRenderItems function.

For the return statement of our App component, we loop through the to-do items and render them, placing the create form at the bottom with the following code:

frontend/src/index.tsx
<div className="App">
<div className="mainContainer">
<div className="header">
complete tasks: {data.done.length}
pending tasks: {data.pending.length}
</div>
<h1>Pending Items</h1>
<div>
{data.pending.map((item, index) => (
<<ToDoItem key={item.title + item.status}
title={item.title}
status={item.status}
id={item.id}
passBackResponse={reRenderItems}/>
</>
))}
</div>
<h1>Done Items</h1>
<div>

[screenshot/content quarantined; see source PDF page 242 for authoritative content]

[figure outside: Figure 7.8]

To style the frontend of our application, we must carry out the following steps:

  1. Serving our CSS
  2. Defining page borders with CSS for different screen sizes
  3. Styling React components with CSS

We are going to serve our CSS by importing our CSS next to our index.tsx file and declaring it in our HTML file so that the CSS is requested by the frontend and served. We also need to bundle our CSS.

First, we import the CSS in our index.tsx file with the following code:

frontend/src/index.tsx
import "./App.css";

This ensures that we will also create a bundle.css file in the public directory when creating a frontend build.

Now, inside our HTML file in the public directory, we have the following:

<!DOCTYPE html>
<html>
<head>
<title>My React App</title>
</head>
<body>
<div id="root"></div>
<link rel="stylesheet" href="./bundle.css">
<script type="module" src="./bundle.js"></script>
</body>
</html>

For our ingress HTML file, we now have the following contents:

<!DOCTYPE html>
<html>
<head>
<title>My To Do App</title>
</head>
<body>
<div id="root"></div>
<link rel="stylesheet" href="./frontend/bundle.css">
<script type="module"
src="./frontend/public/bundle.js"></script>
</body>
</html>

Now that everything is in order, we can focus on our CSS. We can do a basic configuration of the body, which is the App class, with the following code:

/* File: frontend/src/App.css */

.App {
background-color: #92a8d1;
font-family: Arial, Helvetica, sans-serif;
height: 100vh;
}

The background-color line refers to a type of color. This reference might not seem like it makes sense just looking at it, but there are color pickers online where you can see and pick a color, and the reference code is supplied. Some code editors support this functionality, but for quick reference, simply google HTML color picker and you will be spoilt for choice at the number of free online interactive tools that are available.

With the preceding configuration, the background for the entire page will be of the code #92a8d1, which is a navy-blue color. If we had just defined the background-color, most of the page would have a white background; the navy-blue background would only be present where there is content. We get the entire background to be navy blue by setting the height to 100vh. vh is relative to 1% of the height of the viewport. With this, we can deduce that 100vh means the styling we defined in the body occupies 100% of the viewport.

We then define the font for all text, unless overwritten, to Arial, Helvetica, sans-serif. We can see that we have defined multiple fonts in the font-family. This does not mean that all of them are implemented or that there are different fonts for different levels of headers or HTML tags. Instead, this is a fallback mechanism. First, the browser will try and render Arial; if it is not supported by the browser, it will then try and render Helvetica, and if that fails too, it will try and render sans-serif.

We have now defined the general style for our body, but what about different screen sizes? For instance, if we were going to access our application on our phone, it should have different dimensions. We can handle these different screen sizes by defining borders with CSS.

Defining page borders with CSS for different screen sizes

Section titled “Defining page borders with CSS for different screen sizes”

We can see the differences in screen margins with the following figure:

Figure 7.9 – Difference in margins between a phone and a desktop monitor

We can see in Figure 7.9 that the ratio of the margin to the space that is filled up by the to-do items list changes. With a phone, there is not much screen space, so most of the screen needs to be taken up by the to-do item; otherwise, we would not be able to read it. However, if we are using a widescreen desktop monitor, we no longer need most of the screen for the to-do items. In fact, if the ratio were the same, the to-do items would be so stretched in the x-axis that it would be hard to read and, frankly, would not look good. This is where media queries come in. We can have different style conditions based on attributes like the width and height of the window.

We will start with the phone specification. So, if the width of the screen is up to 500 pixels, in our CSS file, we will define the following CSS configuration for our body:

/* File: frontend/src/App.css */

@media(max-width: 500px) {

.App {
padding: 1px;
display: grid;
grid-template-columns: 1fr;
}
}

[figure outside: Figure 7.9]

Here, we can see that the padding around the edge of the page and each element is just one pixel. We also have a grid display. This is where we can define columns and rows. However, we do not use it to its full extent. We just have one column. This means that our to-do items will take up most of the screen, like in the phone depiction of Figure 7.8. Even though we are not using a grid in this context, I have kept it in so you can see the relationship this has to the other configurations for larger screens.

If our screen gets a little bigger, we then split our page into three different vertical columns; however, the ratio of the width of the middle column to that of the columns on either side would be 5:1. This is because our screen still is not very big, and we want our items to still take up most of the screen. We can adjust for this by adding another media query with different parameters:

frontend/src/App.css
@media(min-width: 501px) and (max-width: 550px) {
.App {
padding: 1px;
display: grid;
grid-template-columns: 1fr 5fr 1fr;
}
.mainContainer {
grid-column-start: 2;
}
}

We can also see that for our mainContainer CSS class, where we house our to-do items, we will overwrite the attribute grid-column-start. If we did not, then the mainContainer would be squeezed in the left margin at 1fr width. Instead, we are starting and finishing in the middle at 5fr. We can make our mainContainer span across multiple columns with a grid-column-finish attribute.

If our screen gets larger, we then want to adjust the ratios even more, as we do not want our items’ width to get out of control. To achieve this, we can then define a 3 to 1 ratio for the middle column versus the two side columns, and then a 1 to 1 ratio when the screen width gets higher than 1001px:

frontend/src/App.css
@media(min-width: 551px) and (max-width: 1000px) {
.App {
padding: 1px;
display: grid;
grid-template-columns: 1fr 3fr 1fr;
}
.mainContainer {
grid-column-start: 2;
}
}
@media(min-width: 1001px) {

[figure outside: Figure 7.8]

Displaying Content in the Browser


.App {
padding: 1px;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
.mainContainer {
grid-column-start: 2;
}

Now that we have defined our general CSS for our entire application, we can move on to our item container. If we run our server again, we will see that our items are now centered, as seen in Figure 7.10.

Not Secure 0.0.0.0:8001 ☆ ☠️ ABP ☠️

complete tasks: 1 pending tasks: 2

writing book edit coding edit

washing delete create to do item Create

Figure 7.10 – Our application with margins

Now that our list of items is centered, we can move on to styling the items in our list.

We would like our item to have a different background color, giving us the following definition: /* File: frontend/src/App.css */

[figure outside: Figure 7.10]

.itemContainer {
background: #034f84;
display: flex;
align-items: stretch;
justify-content: space-between;
margin: 0.3rem;
}

We can see that this class has a margin of 0.3. We are using the rem because we want the margin to scale relatively to the font size of the root element.

rem stands for “root em” and is a relative unit of measurement in CSS. It is based on the font size of the root element (). For example, if the root font size is set to 16px, then 1rem equals 16px, 2rem equals 32px, and so on.

The align-items ensures that all the children in the container, including the buttons, stretch to fill the container height. The flex ensures that all items grow and shrink relative to each other and can be displayed next to each other. This will come in handy as we want our action button for the to-do item to sit next to the title. We also want our item to slightly change color if our cursor hovers over it:

/* File: frontend/src/App.css */

.itemContainer:hover {
background: #034f99;
}

Inside an item container, the title of our item is denoted with a paragraph tag. We want to define the style of all the paragraphs in the item containers, but not elsewhere. We define the style of the paragraphs in the container with the following code:

/* File: frontend/src/App.css */

.itemContainer p {
color: white;
display: inline-block;
margin: 0.5rem;
margin-right: 0.4rem;
margin-left: 0.4rem;
}

The inline-block allows the title to be displayed alongside the div, which will be acting as the button for the item. The margin definitions merely stop the title from being right up against the edge of the item container. We also ensure that the paragraph color is white, to stand out against the dark background. With our item titles styled, the only item styling left is the action button, which is either edit or delete. This action button is going to float to the right, with a different background color, so we know where to click. To do this, we define our button style with a class, as outlined in the following code:

/* File: frontend/src/App.css */

.actionButton {
display: inline-block;
float: right;
background: #f7786b;
border: none;
padding: 0.5rem;
padding-left: 2rem;
padding-right: 2rem;
color: white;
align-self: stretch;
}

Here, we’ve defined the display, we made it float to the right, and we’ve defined the background color and padding. With this, we ensure the color changes on the hovering of a cursor over the button by running the following code:

/* File: frontend/src/App.css */

.actionButton:hover {
background: #f7686b;
color: black;
}

Now that we have covered all the styling concepts, we only need to define the styles for the input container. This can be done by running the following code:

/* File: frontend/src/App.css */

.inputContainer {
background: #034f84;
display: flex;
align-items: stretch;
justify-content: space-between;
margin: 0.3rem;
margin-top: 2rem;
}

inputContainer input {

display: inline-block;
margin: 0.4rem;
border: 2px solid transparent;
background: #ffffff;
color: #034f84;
}

While this defines the styling of our input, we want the user to know that they have selected the input so that they can type. We can change the CSS of the input when the input is clicked using focus:

/* File: frontend/src/App.css */

.inputContainer input:focus {
outline: none;
border-color: #f7786b;
box-shadow: 0 0 5px #f7786b;
}

And finally, let’s define the CSS for the header with the following code:

/* File: frontend/src/App.css */

.header {
background: #034f84;
margin-bottom: 0.3rem;
}
.header p {
color: white;
display: inline-block;
margin: 0.5rem;
margin-right: 0.4rem;
margin-left: 0.4rem;
}

And that is it, our system is now ready to run. If we run our server, we should get the view seen in Figure 7.11.

Figure 7.11 – Our finished application

And there we have it, our application is working. Our application can be served by our Rust binary.

In this chapter, we have finally enabled our application to be used by a casual user, as opposed to having to rely on making an API. We built a React application and embedded the React application into the Rust server binary to be served by the Rust server. We built the React application using minimalist tooling, so we understand how the React application is built, packaged, and served. We also covered HTML and CSS concepts to make our frontend application look presentable.

This gave us a dynamic view that automatically updated when we edited, deleted, or created a to-do item. We also explored some basics around CSS and JavaScript to make API calls from the frontend to the backend to get the data needed to render the state of to-do items.

We also explored how frontend assets are served, which enabled us to embed our frontend into the Rust binary to be served by our Rust server. However, we are not going to stop there; in the next chapter, we are going to serve WASM in the frontend.

  1. How is the React application and its CSS served to the frontend?

  2. How can we handle data produced in a child component?

[figure outside: Figure 7.11]

227

  1. How do you ensure that the background color and style standard of certain elements is consistent across all views of the app?
  2. What do we use effect for in a React component?
  3. When will a React component re-render?
  1. The React app is bundled into two files, bundle.js and bundle.css. We serve an HTML file that references the CSS and JS file. These files are then requested from the server and loaded into the browser. The JS file is the React application that gets an HTML tag in the HTML file via ID and renders the outcome. This outcome is inserted into the HTML tag in the served HTML file.

  2. The parent component passes a function to the child component. The child component can then pass data into that function and execute the function. Depending on what the function does, this means that the parent component can be altered.

  3. We can create a CSS class and define the background color and other styling types we want to be universal, such as font type and color. In our App component, we return a div with that CSS class. Inside that div, we put all our components for that application, and these components will inherit the CSS class for the initial div.

  4. The useEffect executes when the React component has been loaded. We can also have dependencies, such as data.

  5. A React component re-renders when the data in useState changes.

Get this book’s PDF copy, code bundle, and more

Section titled “Get this book’s PDF copy, code bundle, and more”

Scan the QR code (or go to packtpub.com/unlock). Search for this book by name, confirm the edition, and then follow the steps on the page.

UNLOCK NOW

Note: Have your invoice handy. Purchases made directly from the Packt website don’t require an invoice.

[blank page]