|
| 1 | +--- |
| 2 | +type: example |
| 3 | +summary: A simple frontend app with a containerized backend |
| 4 | +pcx_content_type: example |
| 5 | +title: Static Frontend, Container Backend |
| 6 | +sidebar: |
| 7 | + order: 3 |
| 8 | +description: A simple frontend app with a containerized backend |
| 9 | +--- |
| 10 | + |
| 11 | +import { WranglerConfig, Details } from "~/components"; |
| 12 | + |
| 13 | +A common pattern is to serve a static frontend application (e.g., React, Vue, Svelte) using Static Assets, |
| 14 | +then pass backend requests to a containerized backend application. |
| 15 | + |
| 16 | +In this example, we'll show an example using a simple `index.html` file served as a static asset, |
| 17 | +but you can select from one of many frontend frameworks. See our [Workers framework examples](/workers/framework-guides/web-apps/) for more information. |
| 18 | + |
| 19 | +For a full example, see the [Static Frontend + Container Backend Template](https://github.com/mikenomitch/static-frontend-container-backend). |
| 20 | + |
| 21 | +## Configure Static Assets and a Container |
| 22 | + |
| 23 | +<WranglerConfig> |
| 24 | +```json |
| 25 | +{ |
| 26 | + "name": "cron-container", |
| 27 | + "main": "src/index.ts", |
| 28 | + "assets": { |
| 29 | + "directory": "./dist", |
| 30 | + "binding": "ASSETS" |
| 31 | + }, |
| 32 | + "containers": [ |
| 33 | + { |
| 34 | + "class_name": "Backend", |
| 35 | + "image": "./Dockerfile", |
| 36 | + } |
| 37 | + ], |
| 38 | + "durable_objects": { |
| 39 | + "bindings": [ |
| 40 | + { |
| 41 | + "class_name": "Backend", |
| 42 | + "name": "BACKEND" |
| 43 | + } |
| 44 | + ] |
| 45 | + }, |
| 46 | + "migrations": [ |
| 47 | + { |
| 48 | + "new_sqlite_classes": [ |
| 49 | + "Backend" |
| 50 | + ], |
| 51 | + "tag": "v1" |
| 52 | + } |
| 53 | + ] |
| 54 | +} |
| 55 | +``` |
| 56 | +</WranglerConfig> |
| 57 | + |
| 58 | +## Add a simple index.html file to serve |
| 59 | + |
| 60 | +Create a simple `index.html` file in the `./dist` directory. |
| 61 | + |
| 62 | +<Details header="index.html"> |
| 63 | +```html |
| 64 | +<!DOCTYPE html> |
| 65 | +<html lang="en"> |
| 66 | + |
| 67 | +<head> |
| 68 | + <meta charset="UTF-8"> |
| 69 | + <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| 70 | + <title>Widgets</title> |
| 71 | + <script defer src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/3.13.3/cdn.min.js"></script> |
| 72 | +</head> |
| 73 | + |
| 74 | +<body> |
| 75 | + <div x-data="widgets()" x-init="fetchWidgets()"> |
| 76 | + <h1>Widgets</h1> |
| 77 | + <div x-show="loading">Loading...</div> |
| 78 | + <div x-show="error" x-text="error" style="color: red;"></div> |
| 79 | + <ul x-show="!loading && !error"> |
| 80 | + <template x-for="widget in widgets" :key="widget.id"> |
| 81 | + <li> |
| 82 | + <span x-text="widget.name"></span> - (ID: <span x-text="widget.id"></span>) |
| 83 | + </li> |
| 84 | + </template> |
| 85 | + </ul> |
| 86 | + |
| 87 | + <div x-show="!loading && !error && widgets.length === 0"> |
| 88 | + No widgets found. |
| 89 | + </div> |
| 90 | + |
| 91 | + </div> |
| 92 | + |
| 93 | + <script> |
| 94 | + function widgets() { |
| 95 | + return { |
| 96 | + widgets: [], |
| 97 | + loading: false, |
| 98 | + error: null, |
| 99 | +
|
| 100 | + async fetchWidgets() { |
| 101 | + this.loading = true; |
| 102 | + this.error = null; |
| 103 | +
|
| 104 | + try { |
| 105 | + const response = await fetch('/api/widgets'); |
| 106 | + if (!response.ok) { |
| 107 | + throw new Error(`HTTP ${response.status}: ${response.statusText}`); |
| 108 | + } |
| 109 | + this.widgets = await response.json(); |
| 110 | + } catch (err) { |
| 111 | + this.error = err.message; |
| 112 | + } finally { |
| 113 | + this.loading = false; |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + } |
| 118 | + </script> |
| 119 | + |
| 120 | +</body> |
| 121 | + |
| 122 | +</html> |
| 123 | +``` |
| 124 | +</Details> |
| 125 | + |
| 126 | +In this example, we are using [Alpine.js](https://alpinejs.dev/) to fetch a list of widgets from `/api/widgets`. |
| 127 | + |
| 128 | +This is meant to be a very simple example, but you can get significantly more complex. |
| 129 | +See [examples of Workers integrating with frontend frameworks](/workers/framework-guides/web-apps/) for more information. |
| 130 | + |
| 131 | +## Define a Worker |
| 132 | + |
| 133 | +Your Worker needs to be able to both serve static assets and route requests to the containerized backend. |
| 134 | + |
| 135 | +In this case, we will pass requests to one of three container instances if the route starts with `/api`, |
| 136 | +and all other requests will be served as static assets. |
| 137 | + |
| 138 | +```javascript |
| 139 | +import { Container, getRandom } from "@cloudflare/containers"; |
| 140 | + |
| 141 | +const INSTANCE_COUNT = 3; |
| 142 | + |
| 143 | +class Backend extends Container { |
| 144 | + defaultPort = 8080; // pass requests to port 8080 in the container |
| 145 | + sleepAfter = "2h"; // only sleep a container if it hasn't gotten requests in 2 hours |
| 146 | +} |
| 147 | + |
| 148 | +export default { |
| 149 | + async fetch(request, env) { |
| 150 | + const url = new URL(request.url); |
| 151 | + if (url.pathname.startsWith("/api")) { |
| 152 | + // note: "getRandom" to be replaced with latency-aware routing in the near future |
| 153 | + const containerInstance = getRandom(env.BACKEND, INSTANCE_COUNT); |
| 154 | + return containerInstance.fetch(request); |
| 155 | + } |
| 156 | + |
| 157 | + return env.ASSETS.fetch(request); |
| 158 | + }, |
| 159 | +}; |
| 160 | +``` |
| 161 | + |
| 162 | +:::note |
| 163 | +This example uses the `getRandom` function, which is a temporary helper that will randomly |
| 164 | +select of of N instances of a Container to route requests to. |
| 165 | + |
| 166 | +In the future, we will provide improved latency-aware load balancing and autoscaling. |
| 167 | + |
| 168 | +This will make scaling stateless instances simple and routing more efficient. See the |
| 169 | +[autoscaling documentation](/containers/scaling-and-routing) for more details. |
| 170 | +::: |
| 171 | + |
| 172 | +## Define a backend container |
| 173 | + |
| 174 | +Your container should be able to handle requests to `/api/widgets`. |
| 175 | + |
| 176 | +In this case, we'll use a simple Golang backend that returns a hard-coded list of widgets. |
| 177 | + |
| 178 | +<Details header="server.go"> |
| 179 | +```go |
| 180 | +package main |
| 181 | + |
| 182 | +import ( |
| 183 | + "encoding/json" |
| 184 | + "log" |
| 185 | + "net/http" |
| 186 | +) |
| 187 | + |
| 188 | +func handler(w http.ResponseWriter, r \*http.Request) { |
| 189 | + widgets := []map[string]interface{}{ |
| 190 | + {"id": 1, "name": "Widget A"}, |
| 191 | + {"id": 2, "name": "Sprocket B"}, |
| 192 | + {"id": 3, "name": "Gear C"}, |
| 193 | + } |
| 194 | + |
| 195 | + w.Header().Set("Content-Type", "application/json") |
| 196 | + w.Header().Set("Access-Control-Allow-Origin", "*") |
| 197 | + json.NewEncoder(w).Encode(widgets) |
| 198 | + |
| 199 | +} |
| 200 | + |
| 201 | +func main() { |
| 202 | + http.HandleFunc("/api/widgets", handler) |
| 203 | + log.Fatal(http.ListenAndServe(":8080", nil)) |
| 204 | +} |
| 205 | + |
| 206 | +``` |
| 207 | +</Details> |
0 commit comments