Deployment

When you are ready to deploy your Yew application to a server, you have various options for deployment.

trunk build --release builds your app in release mode. Set up your HTTP server so that it serves index.html whenever your site is visited, and requests to static paths like index_<hash>.js and index_bg_<hash>.wasm are served with the contents of their respective contents from the dist directory generated by trunk.

Deployment - 图1A note about trunk serve --release

Do not use trunk serve --release to serve your application in production. It should only be used for testing the release build during development

Server configuration

Serving index.html as fallback

If the application uses the Yew router, you must configure the server to return the index.html when asked for a file that it does not have.

An application with Yew router is built as a Single Page Application (SPA). When the user navigates to a URL from within a running client, the router interprets the URL and routes to that page.

But on a fresh load, such as when navigating to the page by entering it in the address bar or refreshing the page, all of these actions are handled by the browser itself, outside the running application. The browser makes a direct request to the server for that URL, bypassing the router. A wrongly configured server would return with status 404 - Not Found.

By returning index.html instead, the app loads as it normally would as if request was for /, until the router notices that the the route is /show/42 and displays the appropriate contents.

Configuring correct MIME-type for Web Assembly asset.

The WASM files must be served with the Content-Type header set to application/wasm MIME-type.

Most servers and hosting services already do this by default. If yours doesn’t, consult its documentation. An incorrect MIME-type will, in most web browsers, result in an error similar to the following:

  1. `WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:
  2. TypeError: WebAssembly: Response has unsupported MIME type 'text/plain' expected 'application/wasm'

Building for Relative Paths

By default, trunk will assume that your site is being served at / and build the site accordingly. This behavior can be overridden by adding <base data-trunk-public-url /> to the index.html file. Trunk rewrites this tag to contain the value passed to --public-url. Yew router automatically detects the presence of <base /> and handles it appropriately.

Customizing behavior using environment variables

It’s common to customize the build environment by using environment variables. Since the app is run in browser, we can’t read the environment variables at runtime. The std::env! macro can be used to obtain a value of an environment variables at compile time.