|
| 1 | +--- |
| 2 | +pcx_content_type: concept |
| 3 | +title: Direct Uploads |
| 4 | +sidebar: |
| 5 | + order: 11 |
| 6 | +head: [] |
| 7 | +description: Upload assets through the Workers API. |
| 8 | +--- |
| 9 | + |
| 10 | +import { |
| 11 | + Badge, |
| 12 | + Description, |
| 13 | + FileTree, |
| 14 | + InlineBadge, |
| 15 | + Render, |
| 16 | + TabItem, |
| 17 | + Tabs, |
| 18 | +} from "~/components"; |
| 19 | + |
| 20 | +:::note |
| 21 | + |
| 22 | +Directly uploading assets via Worker APIs is an advanced approach that most users won't need. Instead, users are encouraged to interact with these APIs through [Wrangler](/workers/static-assets/get-started/#1-create-a-new-worker-project-using-the-cli). |
| 23 | + |
| 24 | +::: |
| 25 | + |
| 26 | +The Workers API empowers users to upload and serve static assets. Users can also fetch assets through an optional [assets binding](/workers/static-assets/binding/). This guide will describe the process for attaching assets to your Worker directly through the Workers API. |
| 27 | + |
| 28 | +```mermaid |
| 29 | +sequenceDiagram |
| 30 | + participant User |
| 31 | + participant Workers API |
| 32 | + User<<->>Workers API: Submit manifest<br/>POST /client/v4/accounts/:accountId/workers/scripts/:scriptName/assets-upload-session |
| 33 | + User<<->>Workers API: Upload files<br/>POST /client/v4/accounts/:accountId/workers/assets/upload?base64=true |
| 34 | + User<<->>Workers API: Upload script version<br/>PUT /client/v4/accounts/:accountId/workers/scripts/:scriptName |
| 35 | +``` |
| 36 | + |
| 37 | +The asset upload flow can be distilled into three distinct phases: registration of a manifest, uploading of the assets, and deployment of the Worker. |
| 38 | + |
| 39 | +## `Upload manifest` |
| 40 | + |
| 41 | +The asset manifest is a ledger which keeps track of files we want to use in our Worker. This manifest is used to track assets associated with each Worker version, and eliminate the need to upload unchanged files prior to a new upload. |
| 42 | + |
| 43 | +The manifest upload request describes each file which we intend to upload. Each file is its own key representing the file path and name, and is an object which contains metadata about the file. |
| 44 | + |
| 45 | +`hash` represents the first 32 characters of the file's hash, while `size` is the size (in bytes) of the file. |
| 46 | + |
| 47 | +```bash title="Example manifest upload request" |
| 48 | +curl -X POST https://api.cloudflare.com/client/v4/accounts/:accountId/workers/scripts/:scriptName/assets-upload-session \ |
| 49 | + --header 'content-type: application/json' \ |
| 50 | + --header 'Authorization: Bearer API_TOKEN' \ |
| 51 | + --data '{ "manifest": { "/filea.html": { "hash": "08f1dfda4574284ab3c21666d1", "size": 12 }, "/fileb.html": { "hash": "4f1c1af44620d531446ceef93f", "size": 23 } } }' |
| 52 | +``` |
| 53 | + |
| 54 | +The resulting response will contain a JWT, which provides authentication during file upload. The JWT is valid for one hour. |
| 55 | + |
| 56 | +In addition to the JWT, the response instructs users how to most optimally batch upload their files. These instructions are encoded in the "buckets" field. Each array in buckets contains a list of file hashes which should be uploaded together. |
| 57 | + |
| 58 | +```bash title="Example manifest upload response" |
| 59 | +{ |
| 60 | + "result": { |
| 61 | + "jwt": "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL3N0YWdpbmcuYXBpLndvcmtlcnMuY2xvdWRmbGFyZS5jb20iLCJhdWQiOiJodHRwczovL3N0YWdpbmcuYXBpLndvcmtlcnMuY2xvdWRmbGFyZS5jb20iLCJleHAiOjE3MzA4MzY4MzksIm5iZiI6MTczMDgzMzIzOSwiaWF0IjoxNzMwODMzMjM5LCJtYW5pZmVzdF9pZCI6IjhkNzRmMzQ0LTcyNmQtNDY1Yi04MjE0LTJmYjMwMTE5NWE5YSJ9.Z3g0RNYshjMFHnM8o4X15PRpIAkgkuztIKOfmEW3ZfkmrDFykZFizclBGJKFoP0eZ1N9ODyFNUkfeikjUDvkAQ", |
| 62 | + "buckets": [ |
| 63 | + [ |
| 64 | + "08f1dfda4574284ab3c21666d1", |
| 65 | + "4f1c1af44620d531446ceef93f" |
| 66 | + ] |
| 67 | + ] |
| 68 | + }, |
| 69 | + "success": true, |
| 70 | + "errors": null, |
| 71 | + "messages": null |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +### `Limitations` |
| 76 | + |
| 77 | +- Each file must be under 25 MiB |
| 78 | +- The overall manifest must not contain more than 20,000 file entries |
| 79 | + |
| 80 | +## `Upload Static Assets` |
| 81 | + |
| 82 | +Users can upload assets by POSTing to https://api.cloudflare.com/client/v4/accounts/:accountID/workers/assets/upload?base64=true. This endpoint requires files be uploaded using multipart/form data. The contents of each file must be base64 encoded, and the `base64` query param must be set to `true`. |
| 83 | + |
| 84 | +The authorization header must be provided as a bearer token, using the JWT from the aforementioned manifest upload call. |
| 85 | + |
| 86 | +Once every file in the manifest has been uploaded, a status code of 201 will be returned, with the `jwt` field present, and containing a final "completion" token which can be used in a deployment of a Worker with assets. This token is valid for 1 hour. |
| 87 | + |
| 88 | +## `Create/Deploy New Version` |
| 89 | + |
| 90 | +[Script](https://developers.cloudflare.com/api/operations/worker-script-upload-worker-module) and [version](https://developers.cloudflare.com/api/operations/worker-versions-upload-version) upload endpoints require specifying a metadata part in the form data. If this is a new Worker, we can provide the completion token from the previous (upload assets) step. This token will be validated by the backend to ensure that all assets have been uploaded. |
| 91 | + |
| 92 | +```bash title="Example Worker Metadata Specifying Completion Token" |
| 93 | +{ |
| 94 | + "main_module": "main.js", |
| 95 | + "assets": { |
| 96 | + "jwt": "<completion_token>" |
| 97 | + }, |
| 98 | + "compatibility_date": "2021-09-14" |
| 99 | +} |
| 100 | +``` |
| 101 | + |
| 102 | +If this is a worker which already exists with assets, and you wish to just re-use the existing set of assets, we do not have to specify the completion token again. Instead, we can provide the `keep_assets` metadata configuration. |
| 103 | + |
| 104 | +```bash title="Example Worker Metadata Specifying keep_assets" |
| 105 | +{ |
| 106 | + "main_module": "main.js", |
| 107 | + "keep_assets": true, |
| 108 | + "compatibility_date": "2021-09-14" |
| 109 | +} |
| 110 | +``` |
| 111 | + |
| 112 | +Asset [routing configuration](/workers/static-assets/routing/#routing-configuration) can be provided in the assets object, such as html_handling and not_found_handling. |
| 113 | + |
| 114 | +```bash title="Example Worker Metadata Specifying Asset Configuration" |
| 115 | +{ |
| 116 | + "main_module": "main.js", |
| 117 | + "assets": { |
| 118 | + "jwt": "<completion_token>", |
| 119 | + "config" { |
| 120 | + "html_handling": "auto-trailing-slash" |
| 121 | + } |
| 122 | + }, |
| 123 | + "compatibility_date": "2021-09-14" |
| 124 | +} |
| 125 | +``` |
| 126 | + |
| 127 | +Optionally, an asset binding can be provided if you wish to fetch and serve assets from within your Worker. |
| 128 | + |
| 129 | +```bash title="Example Worker Metadata Specifying Asset Binding" |
| 130 | +{ |
| 131 | + "main_module": "main.js", |
| 132 | + "assets": { |
| 133 | + ... |
| 134 | + }, |
| 135 | + "bindings": [ |
| 136 | + ... |
| 137 | + { |
| 138 | + "name": "ASSETS", |
| 139 | + "type": "assets" |
| 140 | + } |
| 141 | + ... |
| 142 | + ] |
| 143 | + "compatibility_date": "2021-09-14" |
| 144 | +} |
| 145 | +``` |
| 146 | + |
| 147 | +## `Programmatic Example` |
| 148 | + |
| 149 | +<Tabs> <TabItem label="TypeScript" icon="seti:typescript"> |
| 150 | + |
| 151 | +```ts |
| 152 | +import * as fs from "fs"; |
| 153 | +import * as path from "path"; |
| 154 | +import * as crypto from "crypto"; |
| 155 | +import { FormData, fetch } from "undici"; |
| 156 | + |
| 157 | +const accountId: string = ""; // Replace with your actual account ID |
| 158 | +const authToken: string = ""; // Replace with your actual API token |
| 159 | +const filesDirectory: string = "assets"; // Adjust to your assets directory |
| 160 | +const scriptName: string = "my-new-script"; // Replace with desired script name |
| 161 | + |
| 162 | +interface FileMetadata { |
| 163 | + hash: string; |
| 164 | + size: number; |
| 165 | +} |
| 166 | + |
| 167 | +interface UploadSessionData { |
| 168 | + uploadToken: string; |
| 169 | + buckets: string[][]; |
| 170 | + fileMetadata: Record<string, FileMetadata>; |
| 171 | +} |
| 172 | + |
| 173 | +interface UploadResponse { |
| 174 | + result: { |
| 175 | + jwt: string; |
| 176 | + buckets: string[][]; |
| 177 | + }; |
| 178 | + success: boolean; |
| 179 | + errors: any; |
| 180 | + messages: any; |
| 181 | +} |
| 182 | + |
| 183 | +// Function to calculate the SHA-256 hash of a file and truncate to 32 bits |
| 184 | +function calculateFileHash(filePath: string): { |
| 185 | + fileHash: string; |
| 186 | + fileSize: number; |
| 187 | +} { |
| 188 | + const hash = crypto.createHash("sha256"); |
| 189 | + const fileBuffer = fs.readFileSync(filePath); |
| 190 | + hash.update(fileBuffer); |
| 191 | + const fileHash = hash.digest("hex").slice(0, 32); // Grab the first 32 characters |
| 192 | + const fileSize = fileBuffer.length; |
| 193 | + return { fileHash, fileSize }; |
| 194 | +} |
| 195 | + |
| 196 | +// Function to gather file metadata for all files in the directory |
| 197 | +function gatherFileMetadata(directory: string): Record<string, FileMetadata> { |
| 198 | + const files = fs.readdirSync(directory); |
| 199 | + const fileMetadata: Record<string, FileMetadata> = {}; |
| 200 | + |
| 201 | + files.forEach((file) => { |
| 202 | + const filePath = path.join(directory, file); |
| 203 | + const { fileHash, fileSize } = calculateFileHash(filePath); |
| 204 | + fileMetadata["/" + file] = { |
| 205 | + hash: fileHash, |
| 206 | + size: fileSize, |
| 207 | + }; |
| 208 | + }); |
| 209 | + |
| 210 | + return fileMetadata; |
| 211 | +} |
| 212 | + |
| 213 | +function findMatch( |
| 214 | + fileHash: string, |
| 215 | + fileMetadata: Record<string, FileMetadata>, |
| 216 | +): string { |
| 217 | + for (let prop in fileMetadata) { |
| 218 | + const file = fileMetadata[prop] as FileMetadata; |
| 219 | + if (file.hash === fileHash) { |
| 220 | + return prop; |
| 221 | + } |
| 222 | + } |
| 223 | + throw new Error("unknown fileHash"); |
| 224 | +} |
| 225 | + |
| 226 | +// Function to upload a batch of files using the JWT from the first response |
| 227 | +async function uploadFilesBatch( |
| 228 | + jwt: string, |
| 229 | + fileHashes: string[][], |
| 230 | + fileMetadata: Record<string, FileMetadata>, |
| 231 | +): Promise<string> { |
| 232 | + const form = new FormData(); |
| 233 | + |
| 234 | + fileHashes.forEach(async (bucket) => { |
| 235 | + bucket.forEach((fileHash) => { |
| 236 | + const fullPath = findMatch(fileHash, fileMetadata); |
| 237 | + const relPath = filesDirectory + "/" + path.basename(fullPath); |
| 238 | + const fileBuffer = fs.readFileSync(relPath); |
| 239 | + const base64Data = fileBuffer.toString("base64"); // Convert file to Base64 |
| 240 | + |
| 241 | + form.append( |
| 242 | + fileHash, |
| 243 | + new File([base64Data], fileHash, { |
| 244 | + type: "text/html", // Modify Content-Type header based on type of file |
| 245 | + }), |
| 246 | + fileHash, |
| 247 | + ); |
| 248 | + }); |
| 249 | + |
| 250 | + const response = await fetch( |
| 251 | + `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/assets/upload?base64=true`, |
| 252 | + { |
| 253 | + method: "POST", |
| 254 | + headers: { |
| 255 | + Authorization: `Bearer ${jwt}`, |
| 256 | + }, |
| 257 | + body: form, |
| 258 | + }, |
| 259 | + ); |
| 260 | + |
| 261 | + const data = (await response.json()) as UploadResponse; |
| 262 | + if (data && data.result.jwt) { |
| 263 | + return { completionToken: data.result.jwt }; |
| 264 | + } |
| 265 | + }); |
| 266 | + |
| 267 | + throw new Error("Should have received completion token"); |
| 268 | +} |
| 269 | + |
| 270 | +async function scriptUpload(completionToken: string): Promise<void> { |
| 271 | + const form = new FormData(); |
| 272 | + |
| 273 | + // Configure metadata |
| 274 | + form.append( |
| 275 | + "metadata", |
| 276 | + JSON.stringify({ |
| 277 | + main_module: "index.mjs", |
| 278 | + compatibility_date: "2022-03-11", |
| 279 | + assets: { |
| 280 | + jwt: completionToken, // Provide the completion token from file uploads |
| 281 | + }, |
| 282 | + bindings: [{ name: "ASSETS", type: "assets" }], // Optional assets binding to fetch from user worker |
| 283 | + }), |
| 284 | + ); |
| 285 | + |
| 286 | + // Configure (optional) user worker |
| 287 | + form.append( |
| 288 | + "@index.js", |
| 289 | + new File( |
| 290 | + [ |
| 291 | + "export default {async fetch(request, env) { return new Response('Hello world from user worker!'); }}", |
| 292 | + ], |
| 293 | + "index.mjs", |
| 294 | + { |
| 295 | + type: "application/javascript+module", |
| 296 | + }, |
| 297 | + ), |
| 298 | + ); |
| 299 | + |
| 300 | + const response = await fetch( |
| 301 | + `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${scriptName}`, |
| 302 | + { |
| 303 | + method: "PUT", |
| 304 | + headers: { |
| 305 | + Authorization: `Bearer ${authToken}`, |
| 306 | + }, |
| 307 | + body: form, |
| 308 | + }, |
| 309 | + ); |
| 310 | + |
| 311 | + if (response.status != 200) { |
| 312 | + throw new Error("unexpected status code"); |
| 313 | + } |
| 314 | +} |
| 315 | + |
| 316 | +// Function to make the POST request to start the assets upload session |
| 317 | +async function startUploadSession(): Promise<UploadSessionData> { |
| 318 | + const fileMetadata = gatherFileMetadata(filesDirectory); |
| 319 | + |
| 320 | + const requestBody = JSON.stringify({ |
| 321 | + manifest: fileMetadata, |
| 322 | + }); |
| 323 | + |
| 324 | + const response = await fetch( |
| 325 | + `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${scriptName}/assets-upload-session`, |
| 326 | + { |
| 327 | + method: "POST", |
| 328 | + headers: { |
| 329 | + Authorization: `Bearer ${authToken}`, |
| 330 | + "Content-Type": "application/json", |
| 331 | + "Content-Length": Buffer.byteLength(requestBody).toString(), |
| 332 | + }, |
| 333 | + body: requestBody, |
| 334 | + }, |
| 335 | + ); |
| 336 | + |
| 337 | + const data = (await response.json()) as UploadResponse; |
| 338 | + const jwt = data.result.jwt; |
| 339 | + |
| 340 | + return { |
| 341 | + uploadToken: jwt, |
| 342 | + buckets: data.result.buckets, |
| 343 | + fileMetadata, |
| 344 | + }; |
| 345 | +} |
| 346 | + |
| 347 | +// Begin the upload session by uploading a new manifest |
| 348 | +const { uploadToken, buckets, fileMetadata } = await startUploadSession(); |
| 349 | + |
| 350 | +// If all files are already uploaded, a completion token will be immediately returned. Otherwise, |
| 351 | +// we should upload the missing files |
| 352 | +let completionToken = uploadToken; |
| 353 | +if (buckets.length > 0) { |
| 354 | + completionToken = await uploadFilesBatch(uploadToken, buckets, fileMetadata); |
| 355 | +} |
| 356 | + |
| 357 | +// Once we have uploaded all of our files, we can upload a new script, and assets, with completion token |
| 358 | +scriptUpload(completionToken); |
| 359 | +``` |
| 360 | + |
| 361 | +</TabItem> </Tabs> |
0 commit comments