@fastly/compute-js-static-publish 8.0.0 โ 8.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DOCUMENTATION.md +1227 -0
- package/README.md +9 -2
- package/README.short.md +9 -2
- package/build/cli/cli/commands/manage/publish-content.d.ts.map +1 -1
- package/build/cli/cli/commands/manage/publish-content.js +8 -3
- package/build/cli/cli/commands/scaffold/index.d.ts.map +1 -1
- package/build/cli/cli/commands/scaffold/index.js +39 -18
- package/build/cli/cli/storage/kv-store-provider.d.ts +1 -1
- package/build/cli/cli/storage/kv-store-provider.d.ts.map +1 -1
- package/build/cli/cli/storage/kv-store-provider.js +8 -5
- package/build/cli/cli/storage/s3-storage-provider.d.ts.map +1 -1
- package/build/cli/cli/storage/s3-storage-provider.js +4 -2
- package/build/cli/cli/storage/storage-provider.d.ts +1 -0
- package/build/cli/cli/storage/storage-provider.d.ts.map +1 -1
- package/build/cli/cli/util/api-token.d.ts +2 -1
- package/build/cli/cli/util/api-token.d.ts.map +1 -1
- package/build/cli/cli/util/api-token.js +38 -3
- package/build/cli/cli/util/progress.d.ts +11 -0
- package/build/cli/cli/util/progress.d.ts.map +1 -0
- package/build/cli/cli/util/progress.js +32 -0
- package/build/cli/cli/util/purge.d.ts +9 -1
- package/build/cli/cli/util/purge.d.ts.map +1 -1
- package/build/cli/cli/util/purge.js +16 -8
- package/build/server/server/publisher-server/index.d.ts +1 -0
- package/build/server/server/publisher-server/index.d.ts.map +1 -1
- package/build/server/server/publisher-server/index.js +23 -1
- package/package.json +3 -2
package/DOCUMENTATION.md
ADDED
|
@@ -0,0 +1,1227 @@
|
|
|
1
|
+
# Static Publisher for JavaScript on Fastly Compute
|
|
2
|
+
|
|
3
|
+
> NOTE: `@fastly/compute-js-static-publish` is provided as a Fastly Labs product. Visit the [Fastly Labs](https://www.fastlylabs.com/) site for terms of use.
|
|
4
|
+
|
|
5
|
+
> [!NOTE]
|
|
6
|
+
> v8 adds Beta support for S3-compatible storage, such as Fastly [Object Storage](https://www.fastly.com/products/storage). For more details, see the [S3-compatible storage](#-using-s3-compatible-storage-beta) section.
|
|
7
|
+
|
|
8
|
+
> [!NOTE]
|
|
9
|
+
> These docs are for v7 or newer, a major rewrite that adds powerful new features such as named collections.
|
|
10
|
+
> If you're looking for v6, please check out the [v6 branch](https://github.com/fastly/compute-js-static-publish/tree/v6).
|
|
11
|
+
|
|
12
|
+
> [!WARNING]
|
|
13
|
+
> v7 and newer no longer support module assets. If you require this feature, consider using [v6](https://github.com/fastly/compute-js-static-publish/tree/v6).
|
|
14
|
+
|
|
15
|
+
## ๐ Table of Contents
|
|
16
|
+
|
|
17
|
+
- [โจ Key Features](#-key-features)
|
|
18
|
+
- [๐ Quick Start](#-quick-start)
|
|
19
|
+
- [๐ฆ Fastly KV Store](#-using-the-fastly-kv-store)
|
|
20
|
+
- [๐ S3 Compatible Storage](#-using-s3-compatible-storage-beta) (Beta)
|
|
21
|
+
- [โ๏ธ Configuring `static-publish.rc.js`](#๏ธ-configuring-static-publishrcjs)
|
|
22
|
+
- [๐งพ Config for Publishing and Server: `publish-content.config.js`](#-config-for-publishing-and-server-publish-contentconfigjs)
|
|
23
|
+
- [๐ฆ Collections (Publish, Preview, Promote)](#-collections-publish-preview-promote)
|
|
24
|
+
- [๐งน Cleaning Up](#-cleaning-up)
|
|
25
|
+
- [๐ Content Compression](#-content-compression)
|
|
26
|
+
- [๐งฉ Using PublisherServer in Custom Apps](#-using-publisherserver-in-custom-apps)
|
|
27
|
+
- [๐ฅ Using Published Assets in Your Code](#-using-published-assets-in-your-code)
|
|
28
|
+
- [๐ CLI Reference](#-cli-reference)
|
|
29
|
+
- [๐ Appendix](#-appendix)
|
|
30
|
+
- [๐ Next Steps](#-next-steps)
|
|
31
|
+
|
|
32
|
+
Serve static websites and web apps at the edge — no backends and no CDN invalidation delays.
|
|
33
|
+
|
|
34
|
+
`@fastly/compute-js-static-publish` helps you deploy and serve static files using [Fastly Compute](https://developer.fastly.com/learning/compute/) for fast, cacheable, and content-addressed delivery. The library can be configured to store your data in either of the following:
|
|
35
|
+
* Fastly [Key Value Store](https://www.fastly.com/products/kv-store)
|
|
36
|
+
* S3-compatible storage, such as Fastly [Object Storage](https://www.fastly.com/products/storage) (Beta)
|
|
37
|
+
|
|
38
|
+
## โจ Key Features
|
|
39
|
+
|
|
40
|
+
- ๐ฆ Easy to scaffold and deploy
|
|
41
|
+
- ๐ Content stored using hashed keys, in Fastly KV Store or S3-compatible storage (Beta) including Fastly Object Storage
|
|
42
|
+
- ๐ Publish new content without needing to deploy new Wasm binaries
|
|
43
|
+
- ๐ Organize releases into named collections which can be previewed (e.g. `live`, `staging`, `preview-123`)
|
|
44
|
+
- ๐งผ Cleanup tools to remove expired or orphaned files
|
|
45
|
+
- โ๏ธ Configurable per-collection server configurations (e.g. fallback files)
|
|
46
|
+
- ๐ Supports Brotli/gzip compression, conditional GET, and long cache TTLs
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## ๐ Quick Start
|
|
51
|
+
|
|
52
|
+
### ๐ฆ Using the Fastly KV Store
|
|
53
|
+
|
|
54
|
+
#### 1. Scaffold a Compute App
|
|
55
|
+
|
|
56
|
+
Create a directory for your project, place your static files in `./public`, then type:
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
npx @fastly/compute-js-static-publish@latest \
|
|
60
|
+
--root-dir=./public \
|
|
61
|
+
--kv-store-name=site-content
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
You get a Compute app in `./compute-js` with:
|
|
65
|
+
|
|
66
|
+
- `fastly.toml` (service config)
|
|
67
|
+
- `src/index.js` (entry point)
|
|
68
|
+
- `static-publish.rc.js` (app config)
|
|
69
|
+
- `publish-content.config.js` (publish-time / runtime behavior)
|
|
70
|
+
|
|
71
|
+
Once the application is scaffolded, install dependencies:
|
|
72
|
+
|
|
73
|
+
```sh
|
|
74
|
+
cd compute-js
|
|
75
|
+
npm install
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
#### 2. Preview Locally
|
|
79
|
+
|
|
80
|
+
Type the following — no Fastly account or service required yet!
|
|
81
|
+
|
|
82
|
+
```sh
|
|
83
|
+
npm run dev:publish
|
|
84
|
+
npm run dev:start
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Fastly's [local development environment](https://www.fastly.com/documentation/guides/compute/testing/#running-a-local-testing-server) serves your static website at `http://127.0.0.1:7676`, powered by a simulated KV Store.
|
|
88
|
+
|
|
89
|
+
#### 3. Deploy Your App
|
|
90
|
+
|
|
91
|
+
Ready to go live? All you need is a [free Fastly account](https://www.fastly.com/signup/?tier=free)!
|
|
92
|
+
|
|
93
|
+
```sh
|
|
94
|
+
npm run fastly:deploy
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
The command publishes your Compute app and creates the KV Store. (No content uploaded yet!)
|
|
98
|
+
|
|
99
|
+
#### 4. Publish Content
|
|
100
|
+
|
|
101
|
+
```sh
|
|
102
|
+
npm run fastly:publish
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
This command uploads your static files to the KV Store and applies the server config. Your website is now up and live!
|
|
106
|
+
|
|
107
|
+
`fastly:publish` needs a Fastly API token that can write to the KV Store. Set the `FASTLY_API_TOKEN` environment variable, or add `-- --fastly-api-token=<token>`. The command does not read the token of your Fastly CLI profile. If you are logged in with the Fastly CLI, you can give it that token:
|
|
108
|
+
|
|
109
|
+
```sh
|
|
110
|
+
FASTLY_API_TOKEN=$(npx fastly auth token) npm run fastly:publish
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### ๐ Using S3 Compatible Storage (Beta)
|
|
114
|
+
|
|
115
|
+
#### 1. Scaffold a Compute App
|
|
116
|
+
|
|
117
|
+
Create a directory for your project, place your static files in `./public`, then type:
|
|
118
|
+
|
|
119
|
+
```sh
|
|
120
|
+
npx @fastly/compute-js-static-publish@latest \
|
|
121
|
+
--root-dir=./public \
|
|
122
|
+
--storage-mode=s3 \
|
|
123
|
+
--s3-region=<s3 region> \
|
|
124
|
+
--s3-bucket=<bucket name>
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
> [!NOTE]
|
|
128
|
+
> If the storage requires a custom endpoint, such as is the case with Fastly Object Storage, specify it using `--s3-endpoint=<endpoint>`. For example:
|
|
129
|
+
>
|
|
130
|
+
> ```sh
|
|
131
|
+
> npx @fastly/compute-js-static-publish@latest \
|
|
132
|
+
> --root-dir=./public \
|
|
133
|
+
> --storage-mode=s3 \
|
|
134
|
+
> --s3-region=us-east \
|
|
135
|
+
> --s3-bucket=my-static-content-bucket \
|
|
136
|
+
> --s3-endpoint=https://us-east.object.fastlystorage.app
|
|
137
|
+
> ```
|
|
138
|
+
|
|
139
|
+
You get a Compute app in `./compute-js` with:
|
|
140
|
+
|
|
141
|
+
- `fastly.toml` (service config)
|
|
142
|
+
- `src/index.js` (entry point)
|
|
143
|
+
- `static-publish.rc.js` (app config)
|
|
144
|
+
- `publish-content.config.js` (publish-time / runtime behavior)
|
|
145
|
+
|
|
146
|
+
Once the application is scaffolded, install dependencies:
|
|
147
|
+
|
|
148
|
+
```sh
|
|
149
|
+
cd compute-js
|
|
150
|
+
npm install
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
#### 2. Publish your content to S3-compatible storage
|
|
154
|
+
|
|
155
|
+
Before publishing your content, your S3-compatible bucket must already exist.
|
|
156
|
+
|
|
157
|
+
> [!TIP]
|
|
158
|
+
> If you're using Fastly Object Storage, [create your Fastly account](https://www.fastly.com/signup/?tier=free) if you haven't already, and then follow the [Object Storage quick start](https://www.fastly.com/documentation/guides/platform/object-storage/object-storage-quick-start/) to set up your bucket.
|
|
159
|
+
|
|
160
|
+
Type the following:
|
|
161
|
+
|
|
162
|
+
```sh
|
|
163
|
+
npm run s3:publish
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
#### 3. Preview Locally
|
|
167
|
+
|
|
168
|
+
Type the following to preview your site locally:
|
|
169
|
+
|
|
170
|
+
```sh
|
|
171
|
+
npm run dev:start
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Fastly's [local development environment](https://www.fastly.com/documentation/guides/compute/testing/#running-a-local-testing-server) serves your static website at `http://127.0.0.1:7676`. Your content is fetched from S3-compatible storage.
|
|
175
|
+
|
|
176
|
+
#### 4. Deploy Your App
|
|
177
|
+
|
|
178
|
+
Ready to go live? All you need is a [free Fastly account](https://www.fastly.com/signup/?tier=free)!
|
|
179
|
+
|
|
180
|
+
```sh
|
|
181
|
+
npm run fastly:deploy
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
The app reads the S3 credentials from the Secret Store that has the resource link name `S3_CREDENTIALS` on your service.
|
|
185
|
+
|
|
186
|
+
When the Fastly CLI creates a new service, it creates a Secret Store named `S3_CREDENTIALS`, links it to the service with the same name, and prompts you for the values `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`.
|
|
187
|
+
|
|
188
|
+
---
|
|
189
|
+
|
|
190
|
+
## ๐ Project Layout
|
|
191
|
+
|
|
192
|
+
Here's what your project might look like after scaffolding:
|
|
193
|
+
|
|
194
|
+
```
|
|
195
|
+
my-project/
|
|
196
|
+
โโโ public/ # Your static site files (HTML, CSS, JS, etc.)
|
|
197
|
+
โ โโโ index.html
|
|
198
|
+
โ โโโ scripts.js
|
|
199
|
+
โ โโโ styles.css
|
|
200
|
+
โ โโโ (... other static files ...)
|
|
201
|
+
โโโ compute-js/ # The scaffolded Compute application
|
|
202
|
+
โโโ fastly.toml # Fastly service configuration
|
|
203
|
+
โโโ package.json # Scaffolded package metadata
|
|
204
|
+
โโโ package-lock.json # Dependency lockfile
|
|
205
|
+
โโโ .gitignore # Ignores build artifacts by default
|
|
206
|
+
โโโ static-publish.rc.js # App config
|
|
207
|
+
โโโ publish-content.config.js # Publishing / runtime config
|
|
208
|
+
โโโ static-publisher/ # โ ๏ธ Do not commit - generated content for local dev and publishing
|
|
209
|
+
โ โโโ kvstore.json # Simulates KV Store content for local preview
|
|
210
|
+
โ โโโ kv-store-content/ # Preprocessed and compressed files for KV upload
|
|
211
|
+
โโโ src/
|
|
212
|
+
โโโ index.js # Your Compute app entry point
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
## โ๏ธ Configuring `static-publish.rc.js`
|
|
216
|
+
|
|
217
|
+
This file defines your compute-js-static-publish application's settings. A copy of this is also baked into the Wasm binary and loaded when running your Compute app locally or on the edge.
|
|
218
|
+
|
|
219
|
+
> [!NOTE]
|
|
220
|
+
> Making changes to this file requires rebuilding the Compute app, since a copy of it is baked into the Wasm binary.
|
|
221
|
+
|
|
222
|
+
### Using the Fastly KV Store
|
|
223
|
+
|
|
224
|
+
#### Fields:
|
|
225
|
+
|
|
226
|
+
All fields are required unless specified otherwise.
|
|
227
|
+
|
|
228
|
+
- `storageMode` - Specifies the storage mode. Set to `'kv-store'`.
|
|
229
|
+
- `kvStore.kvStoreName` - The name of the KV Store used for publishing.
|
|
230
|
+
- `defaultCollectionName` - Collection to serve when none is specified.
|
|
231
|
+
- `publishId` - Unique prefix for all keys in the KV Store. Override only for advanced setups (e.g., multiple apps sharing the same KV Store).
|
|
232
|
+
- `staticPublisherWorkingDir` - Directory to hold working files during publish.
|
|
233
|
+
|
|
234
|
+
#### Example: `static-publish.rc.js`
|
|
235
|
+
|
|
236
|
+
```js
|
|
237
|
+
const rc = {
|
|
238
|
+
storageMode: 'kv-store',
|
|
239
|
+
kvStore: {
|
|
240
|
+
kvStoreName: 'site-content',
|
|
241
|
+
},
|
|
242
|
+
defaultCollectionName: 'live',
|
|
243
|
+
publishId: 'default',
|
|
244
|
+
staticPublisherWorkingDir: './static-publisher',
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
export default rc;
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
### Using S3-compatible storage (BETA)
|
|
251
|
+
|
|
252
|
+
#### Fields:
|
|
253
|
+
|
|
254
|
+
All fields are required unless specified otherwise.
|
|
255
|
+
|
|
256
|
+
- `storageMode` - Specifies the storage mode. Set to `'s3'`.
|
|
257
|
+
- `s3.region` - The region of the S3-compatible bucket.
|
|
258
|
+
- `s3.bucket` - The name of the S3-compatible bucket.
|
|
259
|
+
- `s3.endpoint` - (optional) The custom endpoint for the S3-compatible bucket.
|
|
260
|
+
- `defaultCollectionName` - Collection to serve when none is specified.
|
|
261
|
+
- `publishId` - Unique prefix for all keys in the bucket. Override only for advanced setups (e.g., multiple apps sharing the same bucket).
|
|
262
|
+
- `staticPublisherWorkingDir` - Directory to hold working files during publish.
|
|
263
|
+
|
|
264
|
+
#### Example: `static-publish.rc.js`
|
|
265
|
+
|
|
266
|
+
```js
|
|
267
|
+
const rc = {
|
|
268
|
+
storageMode: 's3',
|
|
269
|
+
s3: {
|
|
270
|
+
region: 'us-east-1',
|
|
271
|
+
bucket: 'my-site-content',
|
|
272
|
+
},
|
|
273
|
+
defaultCollectionName: 'live',
|
|
274
|
+
publishId: 'default',
|
|
275
|
+
staticPublisherWorkingDir: './static-publisher',
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
export default rc;
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
## ๐งพ Config for Publishing and Server: `publish-content.config.js`
|
|
282
|
+
|
|
283
|
+
This file is included as part of the scaffolding. Every time you publish content, the publish settings in this file are used for publishing the content, and the server settings are taken from this file and saved as the settings used by the server for that collection.
|
|
284
|
+
|
|
285
|
+
```js
|
|
286
|
+
const config = {
|
|
287
|
+
// these paths are relative to compute-js dir
|
|
288
|
+
rootDir: '../public',
|
|
289
|
+
|
|
290
|
+
// Include/exclude filters (optional):
|
|
291
|
+
excludeDirs: ['node_modules'],
|
|
292
|
+
excludeDotFiles: true,
|
|
293
|
+
includeWellKnown: true,
|
|
294
|
+
|
|
295
|
+
// Advanced filtering (optional):
|
|
296
|
+
assetInclusionTest: (key, contentType) => {
|
|
297
|
+
return true; // include everything by default
|
|
298
|
+
},
|
|
299
|
+
|
|
300
|
+
// Override which compressed variants to create for each asset during publish (optional):
|
|
301
|
+
contentCompression: ['br', 'gzip'],
|
|
302
|
+
|
|
303
|
+
// Brotli quality, 0 to 11 (optional, default 11):
|
|
304
|
+
brotliQuality: 11,
|
|
305
|
+
|
|
306
|
+
// Content type definitions/overrides (optional):
|
|
307
|
+
contentTypes: [
|
|
308
|
+
{ test: /\.custom$/, contentType: 'application/x-custom', text: false },
|
|
309
|
+
],
|
|
310
|
+
|
|
311
|
+
// Server settings
|
|
312
|
+
server: {
|
|
313
|
+
spaFile: '/spa.html',
|
|
314
|
+
notFoundPageFile: '/404.html',
|
|
315
|
+
autoIndex: ['index.html'],
|
|
316
|
+
autoExt: ['.html'],
|
|
317
|
+
staticItems: ['/static/', '/assets/'],
|
|
318
|
+
allowedEncodings: ['br', 'gzip'],
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
export default config;
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
You can override this file for a single `publish-content` command by specifying an alternative using `--config` on the command line.
|
|
326
|
+
|
|
327
|
+
### Fields:
|
|
328
|
+
|
|
329
|
+
- `rootDir` - Directory to scan for content, relative to this file (required).
|
|
330
|
+
- `excludeDirs` - Array of directory names or regex patterns to exclude (default: `['./node_modules']`).
|
|
331
|
+
- `excludeDotFiles` - Exclude dotfiles and dot-named directories (default: true).
|
|
332
|
+
- `includeWellKnown` - Always include `.well-known` even if dotfiles are excluded (default: true).
|
|
333
|
+
- `assetInclusionTest` - Function to determine inclusion and variant behavior per file.
|
|
334
|
+
- `contentCompression` - Array of compression formats to pre-generate (`['br', 'gzip']` by default).
|
|
335
|
+
- `brotliQuality` - Brotli quality for the `br` variants, an integer from 0 to 11 (default: 11). Quality 11 gives the smallest files but is the slowest. Quality 10 is approximately 3 times faster, and its files are approximately 2% larger. If you change this value, variants that are already in storage are not compressed again.
|
|
336
|
+
- `contentTypes` - Additional or override content type definitions.
|
|
337
|
+
|
|
338
|
+
- `server` - Server runtime config that contains the following fields:
|
|
339
|
+
- `publicDirPrefix` - **Deprecated.** A future version will remove it.
|
|
340
|
+
A prefix that the Publisher Server adds to the path of each
|
|
341
|
+
request, to get the asset key. Use it if the files to serve are in a subdirectory
|
|
342
|
+
of `rootDir`. For example, if `rootDir` is `'../site'` and the files to serve are in
|
|
343
|
+
`'../site/public'`, set it to `'/public'`. The value starts with `/` and does not
|
|
344
|
+
end with `/` (default: `''`). The scaffolder sets it from `--root-dir` and `--public-dir`.
|
|
345
|
+
- `spaFile` - Path to a file to be used to serve in a SPA application.
|
|
346
|
+
- `notFoundPageFile` - Path to a file to be used to serve as a 404 not found page.
|
|
347
|
+
- `autoIndex` - List of files to automatically use as index.
|
|
348
|
+
- `autoExt` - List of extensions to automatically apply to a path and retry when
|
|
349
|
+
the requested path is not found.
|
|
350
|
+
- `staticItems` - Directories to specify as containing 'static' files. The
|
|
351
|
+
Publisher Server will serve files from these directories with a long TTL.
|
|
352
|
+
- `allowedEncodings` - Specifies which compression formats the server is allowed
|
|
353
|
+
to serve based on the client's `Accept-Encoding` header.
|
|
354
|
+
|
|
355
|
+
## ๐ฆ Collections (Publish, Preview, Promote)
|
|
356
|
+
|
|
357
|
+
Collections are a powerful feature that allow you to publish and manage multiple versions of your site simultaneously. Each collection is a named set of:
|
|
358
|
+
|
|
359
|
+
- Static files
|
|
360
|
+
- Server configuration (e.g., fallback file, static directories, etc.)
|
|
361
|
+
- An index file that maps paths to those hashes
|
|
362
|
+
|
|
363
|
+
Collections are published using a `--collection-name`, and can be reused, updated, or deleted independently. For example, you can create a staging version of your site using:
|
|
364
|
+
|
|
365
|
+
```sh
|
|
366
|
+
npx @fastly/compute-js-static-publish publish-content \
|
|
367
|
+
--collection-name=staging \
|
|
368
|
+
--expires-in=7d \
|
|
369
|
+
--config=./publish-content.config.js
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
You can overwrite or republish any collection at any time. Old file hashes will be reused automatically where contents match.
|
|
373
|
+
|
|
374
|
+
### Expiration (Auto-cleanup)
|
|
375
|
+
|
|
376
|
+
Collections can expire automatically:
|
|
377
|
+
|
|
378
|
+
- Expired collections are ignored by the server and return 404s
|
|
379
|
+
- A request for a collection other than the default collection that is expired or not published gets a plain-text 404 that names the collection. The response cache does not store it, so the collection is served as soon as you publish it. If the default collection is not published, the server returns a 500.
|
|
380
|
+
- The default collection never expires
|
|
381
|
+
- Expiration limits can be modified (shortened, extended, reenstated) using `collections update-expiration`
|
|
382
|
+
- They are cleaned up by `clean --delete-expired-collections`
|
|
383
|
+
|
|
384
|
+
```sh
|
|
385
|
+
--expires-in=3d # relative (e.g. 1h, 2d, 1w)
|
|
386
|
+
--expires-at=2025-05-01T12:00Z # absolute (ISO 8601)
|
|
387
|
+
--expires-never # the collection never expires
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
*(Only one of **`--expires-in`**, **`--expires-at`**, or **`--expires-never`** may be specified)*
|
|
391
|
+
|
|
392
|
+
### Switching the active collection
|
|
393
|
+
|
|
394
|
+
By default, the server app serves assets from the "default collection", named in `static-publish.rc.js` under `defaultCollectionName`. To switch the active collection, you add custom code to your Compute app that calls `publisherServer.setActiveCollectionName(name)`:
|
|
395
|
+
|
|
396
|
+
```js
|
|
397
|
+
publisherServer.setActiveCollectionName("preview-42");
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
Pass `null` to select the default collection.
|
|
401
|
+
|
|
402
|
+
If the app turns on sandbox reuse, Compute can use a sandbox for more than one request (see [Sandbox lifecycle](https://www.fastly.com/documentation/guides/compute/developer-guides/sandbox-lifecycle/)), and the active collection stays set until you change it. Thus, call `setActiveCollectionName()` for each request, also when the request does not select a collection.
|
|
403
|
+
|
|
404
|
+
#### Example: Subdomain-based Routing
|
|
405
|
+
|
|
406
|
+
In the following example, assume that the Compute application is hosted using a wildcard domain `*.example.com`. A request for `preview-pr-123.example.com` would activate the collection `'pr-123'`.
|
|
407
|
+
|
|
408
|
+
```js
|
|
409
|
+
import { PublisherServer, collectionSelector } from '@fastly/compute-js-static-publish';
|
|
410
|
+
import rc from '../static-publish.rc.js';
|
|
411
|
+
|
|
412
|
+
const publisherServer = PublisherServer.fromStaticPublishRc(rc);
|
|
413
|
+
|
|
414
|
+
addEventListener("fetch", event => {
|
|
415
|
+
const request = event.request;
|
|
416
|
+
const collectionName = collectionSelector.fromHostDomain(request, /^preview-([^\.]*)\./);
|
|
417
|
+
publisherServer.setActiveCollectionName(collectionName); // null selects the default collection
|
|
418
|
+
|
|
419
|
+
event.respondWith(publisherServer.serveRequest(request));
|
|
420
|
+
});
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
### ๐ Selecting a Collection at Runtime
|
|
424
|
+
|
|
425
|
+
The `collectionSelector` module provides helpers to extract a collection name from different parts of a request:
|
|
426
|
+
|
|
427
|
+
```js
|
|
428
|
+
collectionSelector.fromHostDomain(request, /^preview-([^\.]*)\./);
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
#### From the Request URL
|
|
432
|
+
|
|
433
|
+
```js
|
|
434
|
+
collectionSelector.fromRequestUrl(request, url => url.pathname.split('/')[2]);
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
#### With a Custom Request Matcher
|
|
438
|
+
|
|
439
|
+
```js
|
|
440
|
+
collectionSelector.fromRequest(request, req => req.headers.get('x-collection') ?? 'live');
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
#### From a Cookie
|
|
444
|
+
|
|
445
|
+
See [fromCookie](#fromcookie) for details on this feature.
|
|
446
|
+
|
|
447
|
+
```js
|
|
448
|
+
const { collectionName, redirectResponse } = collectionSelector.fromCookie(request);
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
#### From a Fastly Config Store
|
|
452
|
+
|
|
453
|
+
```js
|
|
454
|
+
collectionSelector.fromConfigStore('my-config-store', 'collection-key');
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
### ๐ Promoting a Collection
|
|
458
|
+
|
|
459
|
+
If you're happy with a preview or staging collection and want to make it live, use the `collections promote` command:
|
|
460
|
+
|
|
461
|
+
```sh
|
|
462
|
+
npx @fastly/compute-js-static-publish collections promote \
|
|
463
|
+
--collection-name=staging
|
|
464
|
+
--to=live
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
This copies all content and server settings from the `staging` collection to `live`.
|
|
468
|
+
|
|
469
|
+
You can also specify a new expiration:
|
|
470
|
+
|
|
471
|
+
```sh
|
|
472
|
+
npx @fastly/compute-js-static-publish collections promote \
|
|
473
|
+
--collection-name=preview-42 \
|
|
474
|
+
--to=staging \
|
|
475
|
+
--expires-in=7d
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
> [!NOTE]
|
|
479
|
+
> The collection denoted by `defaultCollectionName` is exempt from expiration.
|
|
480
|
+
|
|
481
|
+
## ๐ Development โ Production Workflow
|
|
482
|
+
|
|
483
|
+
### Using the KV Store
|
|
484
|
+
|
|
485
|
+
#### Local development
|
|
486
|
+
|
|
487
|
+
During development, the local development server (`npm run dev:start`) runs against assets loaded into the simulated KV Store provided by the local development environment.
|
|
488
|
+
|
|
489
|
+
Prior to starting the server, publish the content to the simulated KV Store:
|
|
490
|
+
|
|
491
|
+
```sh
|
|
492
|
+
npm run dev:publish # 'publish' your files to the simulated local KV Store
|
|
493
|
+
npm run dev:start # preview locally
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
This simulates publishing by writing to `kvstore.json` instead of uploading to the actual KV Store. You can preview your site at `http://127.0.0.1:7676` - no Fastly account or service required.
|
|
497
|
+
|
|
498
|
+
Note that for local development, you will have to stop and restart the local development server each time you publish updates to your content.
|
|
499
|
+
|
|
500
|
+
To publish to an alternative collection name, use the following command and then restart the local development server:
|
|
501
|
+
|
|
502
|
+
```sh
|
|
503
|
+
npm run dev:publish -- --collection-name=preview-123
|
|
504
|
+
```
|
|
505
|
+
|
|
506
|
+
#### Production
|
|
507
|
+
|
|
508
|
+
When you're ready for production:
|
|
509
|
+
|
|
510
|
+
1. [Create a free Fastly account](https://www.fastly.com/signup/?tier=free) if you haven't already.
|
|
511
|
+
2. Run `npm run fastly:deploy`
|
|
512
|
+
- This builds your Compute app into a Wasm binary
|
|
513
|
+
- Deploys it to a new or existing Fastly Compute service
|
|
514
|
+
- If creating a new service:
|
|
515
|
+
- you'll be prompted for backend info - **you can skip this**, as no backend is needed (all content is served from KV)
|
|
516
|
+
- KV Store will be created if necessary and automatically linked to your new service.
|
|
517
|
+
|
|
518
|
+
Once deployed, publish content like so:
|
|
519
|
+
|
|
520
|
+
```sh
|
|
521
|
+
npm run fastly:publish
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
`fastly:publish` needs a Fastly API token that can write to the KV Store. Set the `FASTLY_API_TOKEN` environment variable, or add `-- --fastly-api-token=<token>`. The command does not read the token of your Fastly CLI profile. If you are logged in with the Fastly CLI, you can give it that token:
|
|
525
|
+
|
|
526
|
+
```sh
|
|
527
|
+
FASTLY_API_TOKEN=$(npx fastly auth token) npm run fastly:publish
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
This:
|
|
531
|
+
|
|
532
|
+
- Uses the default collection name
|
|
533
|
+
- Uploads static files to the KV Store
|
|
534
|
+
- Stores server configuration for the collection
|
|
535
|
+
|
|
536
|
+
> [!TIP]
|
|
537
|
+
> Upload to a specific collection by specifying the collection name when publishing content:
|
|
538
|
+
> ```sh
|
|
539
|
+
> npm run fastly:publish -- --collection-name=preview-42
|
|
540
|
+
> ```
|
|
541
|
+
|
|
542
|
+
**No Wasm redeploy needed** unless you:
|
|
543
|
+
|
|
544
|
+
- Modify `src/index.js` - such as when you update your custom routing logic (e.g. collection selection) or
|
|
545
|
+
- Change `static-publish.rc.js`
|
|
546
|
+
|
|
547
|
+
If you do need to rebuild and redeploy the Compute app, simply run:
|
|
548
|
+
|
|
549
|
+
```sh
|
|
550
|
+
npm run fastly:deploy
|
|
551
|
+
```
|
|
552
|
+
|
|
553
|
+
### Using S3-compatible storage (BETA)
|
|
554
|
+
|
|
555
|
+
#### Local development
|
|
556
|
+
|
|
557
|
+
During development, the local development server (`npm run dev:start`) runs against assets published to S3-compatible storage.
|
|
558
|
+
|
|
559
|
+
In this mode, the content in the S3-compatible storage can be updated independent of the Compute application running in the local development server.
|
|
560
|
+
|
|
561
|
+
Before publishing your content, your S3-compatible bucket must already exist.
|
|
562
|
+
|
|
563
|
+
> [!TIP]
|
|
564
|
+
> If you're using Fastly Object Storage, [create your Fastly account](https://www.fastly.com/signup/?tier=free) if you haven't already, and then follow the [Object Storage quick start](https://www.fastly.com/documentation/guides/platform/object-storage/object-storage-quick-start/) to set up your bucket.
|
|
565
|
+
|
|
566
|
+
Publish your content by typing:
|
|
567
|
+
|
|
568
|
+
```sh
|
|
569
|
+
npm run s3:publish
|
|
570
|
+
```
|
|
571
|
+
|
|
572
|
+
Then start the local development server:
|
|
573
|
+
|
|
574
|
+
```sh
|
|
575
|
+
npm run dev:start
|
|
576
|
+
```
|
|
577
|
+
|
|
578
|
+
#### Production
|
|
579
|
+
|
|
580
|
+
When you're ready for production:
|
|
581
|
+
|
|
582
|
+
1. [Create a free Fastly account](https://www.fastly.com/signup/?tier=free) if you haven't already.
|
|
583
|
+
2. Run `npm run fastly:deploy`
|
|
584
|
+
- This builds your Compute app into a Wasm binary
|
|
585
|
+
- Deploys it to a new or existing Fastly Compute service
|
|
586
|
+
- If creating a new service, the Fastly CLI uses the `[setup]` section of `fastly.toml`:
|
|
587
|
+
- It creates the backend `s3_storage`. It prompts you for the hostname and the port of the backend.
|
|
588
|
+
The default values are the hostname of your S3 endpoint and 443. Press Enter to accept them.
|
|
589
|
+
- It creates the Secret Store `S3_CREDENTIALS` and prompts you for the values of
|
|
590
|
+
`S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`. Use credentials that can read the bucket.
|
|
591
|
+
- It links the backend and the Secret Store to your new service.
|
|
592
|
+
- If you deploy to an existing service, the Fastly CLI does not use the `[setup]` section.
|
|
593
|
+
Add the backend and the Secret Store to the service yourself, with the same names.
|
|
594
|
+
|
|
595
|
+
Once deployed, publish content like so:
|
|
596
|
+
|
|
597
|
+
```sh
|
|
598
|
+
npm run s3:publish
|
|
599
|
+
```
|
|
600
|
+
|
|
601
|
+
After the deploy, `fastly.toml` has the service ID, so `s3:publish` also purges the service's cache. For this purge, set `FASTLY_API_TOKEN` (or add `-- --fastly-api-token=<token>`) in addition to the S3 credentials. Without it, `s3:publish` stops with an error before it uploads files.
|
|
602
|
+
|
|
603
|
+
This:
|
|
604
|
+
|
|
605
|
+
- Uses the default collection name
|
|
606
|
+
- Uploads static files to the S3-compatible bucket
|
|
607
|
+
- Stores server configuration for the collection
|
|
608
|
+
|
|
609
|
+
> [!TIP]
|
|
610
|
+
> Upload to a specific collection by specifying the collection name when publishing content:
|
|
611
|
+
> ```sh
|
|
612
|
+
> npm run s3:publish -- --collection-name=preview-42
|
|
613
|
+
> ```
|
|
614
|
+
|
|
615
|
+
**No Wasm redeploy needed** unless you:
|
|
616
|
+
|
|
617
|
+
- Modify `src/index.js` - such as when you update your custom routing logic (e.g. collection selection) or
|
|
618
|
+
- Change `static-publish.rc.js`
|
|
619
|
+
|
|
620
|
+
If you do need to rebuild and redeploy the Compute app, simply run:
|
|
621
|
+
|
|
622
|
+
```sh
|
|
623
|
+
npm run fastly:deploy
|
|
624
|
+
```
|
|
625
|
+
|
|
626
|
+
## ๐งน Cleaning Up
|
|
627
|
+
|
|
628
|
+
Every time you publish, old files are left behind for safety. **However, files with the same content will be re-used across collections and publishing events.** They are only stored once in the KV Store using their content hash as a key. This ensures that unchanged files aren't duplicated, keeping storage efficient and deduplicated.
|
|
629
|
+
|
|
630
|
+
Over time, however, collections may expire, old versions of files will be left behind, and some assets in the KV Store will no longer be referenced by any live collection. To avoid bloat, use:
|
|
631
|
+
|
|
632
|
+
```sh
|
|
633
|
+
npm run dev:clean
|
|
634
|
+
```
|
|
635
|
+
and
|
|
636
|
+
```sh
|
|
637
|
+
npm run fastly:clean
|
|
638
|
+
```
|
|
639
|
+
|
|
640
|
+
These scripts run against the local and Fastly KV Stores respectively, and run the following command:
|
|
641
|
+
```
|
|
642
|
+
npx @fastly/compute-js-static-publish clean --delete-expired-collections
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
This removes:
|
|
646
|
+
|
|
647
|
+
- Expired collection index files (only if `--delete-expired-collections` is passed)
|
|
648
|
+
- Unused content blobs (no longer referenced)
|
|
649
|
+
- Orphaned server config files
|
|
650
|
+
|
|
651
|
+
### ๐ Dry Run Mode
|
|
652
|
+
|
|
653
|
+
Preview what will be deleted without making changes:
|
|
654
|
+
|
|
655
|
+
```sh
|
|
656
|
+
npx @fastly/compute-js-static-publish clean --dry-run
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
> โ ๏ธ Cleanup never deletes the default collection and never deletes content thatโs still in use.
|
|
660
|
+
|
|
661
|
+
## ๐ Content Compression
|
|
662
|
+
|
|
663
|
+
This project supports pre-compressing and serving assets in Brotli and Gzip formats. Compression is controlled at two different stages:
|
|
664
|
+
|
|
665
|
+
- **During publishing**, the `contentCompression` field in the `publish` section of `publish-content.config.js` defines which compressed variants (e.g., `br`, `gzip`) should be generated and uploaded to storage.
|
|
666
|
+
|
|
667
|
+
Assets are stored in multiple formats (uncompressed + compressed) if configured. A compressed variant is uploaded and used only if it is smaller than the original. (For very small files, the compressed variant is often larger.) If a variant is already in storage, it is not compressed or uploaded again. Files are compressed in parallel on the Node.js thread pool. By default, the CLI sets `UV_THREADPOOL_SIZE` to the number of CPU cores (minimum 4, maximum 16). To use a different value, set `UV_THREADPOOL_SIZE` yourself. To make compression faster, you can also set a lower `brotliQuality`. The following file types are compressed by default:
|
|
668
|
+
|
|
669
|
+
- Text-based: `.html`, `.js`, `.css`, `.svg`, `.json`, `.txt`, `.xml`, `.map`
|
|
670
|
+
- Certain binary formats: `.bmp`, `.tar`
|
|
671
|
+
|
|
672
|
+
- **At runtime**, the `allowedEncodings` field in the `server` section of `publish-content.config.js` specifies which compression formats the server is allowed to serve based on the client's `Accept-Encoding` header.
|
|
673
|
+
|
|
674
|
+
`PublisherServer` will serve the smallest appropriate version based on the `Accept-Encoding` header.
|
|
675
|
+
|
|
676
|
+
## ๐งฉ Using PublisherServer in Custom Apps
|
|
677
|
+
|
|
678
|
+
You can combine PublisherServer with custom logic to support APIs, authentication, redirects, or A/B testing. `PublisherServer` returns `null` when it cannot handle a request, allowing you to chain in your own logic.
|
|
679
|
+
|
|
680
|
+
```js
|
|
681
|
+
import { PublisherServer } from '@fastly/compute-js-static-publish';
|
|
682
|
+
import rc from '../static-publish.rc.js';
|
|
683
|
+
|
|
684
|
+
const publisherServer = PublisherServer.fromStaticPublishRc(rc);
|
|
685
|
+
|
|
686
|
+
addEventListener("fetch", event => {
|
|
687
|
+
event.respondWith(handleRequest(event.request));
|
|
688
|
+
});
|
|
689
|
+
|
|
690
|
+
async function handleRequest(request) {
|
|
691
|
+
const response = await publisherServer.serveRequest(request);
|
|
692
|
+
if (response) {
|
|
693
|
+
return response;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// Add your custom logic here
|
|
697
|
+
const url = new URL(request.url);
|
|
698
|
+
if (url.pathname === '/api/hello') {
|
|
699
|
+
return new Response(JSON.stringify({ greeting: "hi" }), {
|
|
700
|
+
headers: { 'content-type': 'application/json' }
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
return new Response("Not Found", { status: 404 });
|
|
705
|
+
}
|
|
706
|
+
```
|
|
707
|
+
|
|
708
|
+
### โฑ๏ธ Measuring Performance with `Server-Timing`
|
|
709
|
+
|
|
710
|
+
`PublisherServer` can report how long it spends reading from storage. To turn this on, give it the name of a request header:
|
|
711
|
+
|
|
712
|
+
```js
|
|
713
|
+
publisherServer.setServerTimingRequestHeader('X-Publisher-Server-Timing');
|
|
714
|
+
```
|
|
715
|
+
|
|
716
|
+
A request that has this header gets a [`Server-Timing`](https://www.w3.org/TR/server-timing/) response header. Requests without it are not affected. This is off by default.
|
|
717
|
+
|
|
718
|
+
```
|
|
719
|
+
Server-Timing: settings;dur=12.3, index;dur=40.1, index-body;dur=31.0, index-parse;dur=24.2, asset;dur=11.4
|
|
720
|
+
```
|
|
721
|
+
|
|
722
|
+
| Name | Duration of |
|
|
723
|
+
|------|-------------|
|
|
724
|
+
| `settings` | Reading and parsing the collection's settings |
|
|
725
|
+
| `index` | Reading the collection's index, until the response headers arrive |
|
|
726
|
+
| `index-body` | Reading the body of the index |
|
|
727
|
+
| `index-parse` | Parsing the index |
|
|
728
|
+
| `asset` | Reading the file, until the response headers arrive. Can appear more than one time, one time for each variant that is tried. |
|
|
729
|
+
| `cache` | Looking up the response cache, if it is on (see [Caching Responses with the Core Cache](#๏ธ-caching-responses-with-the-core-cache)). `desc` is `hit` (with the age of the cached response, for example `hit age=42s`), `miss`, or `bypass`. |
|
|
730
|
+
|
|
731
|
+
An entry is missing if `PublisherServer` did not read that item for this request, for example because the item is cached in memory, or because the response came from the response cache.
|
|
732
|
+
|
|
733
|
+
`serveRequest()` starts the measurements for each request. If you call `getMatchingAsset()` and `serveAsset()` directly, call `beginRequest()` first:
|
|
734
|
+
|
|
735
|
+
```js
|
|
736
|
+
publisherServer.beginRequest(request);
|
|
737
|
+
const asset = await publisherServer.getMatchingAsset(pathname);
|
|
738
|
+
if (asset != null) {
|
|
739
|
+
return publisherServer.serveAsset(request, asset);
|
|
740
|
+
}
|
|
741
|
+
```
|
|
742
|
+
|
|
743
|
+
Any client can send the request header. Choose a name that is not easy to guess if you do not want to show these timings to the public.
|
|
744
|
+
|
|
745
|
+
### ๐๏ธ Caching Responses with the Core Cache
|
|
746
|
+
|
|
747
|
+
To serve a file, `PublisherServer` reads the collection's settings, the collection's index, and the file. Fastly can cache these reads, but `PublisherServer` must still parse the index for each request, and the index of a large site is large. To skip this work, `PublisherServer` can cache whole responses with the Fastly [Core Cache](https://www.fastly.com/documentation/guides/concepts/cache/) API:
|
|
748
|
+
|
|
749
|
+
```js
|
|
750
|
+
publisherServer.setResponseCache({ maxAge: 3600 });
|
|
751
|
+
```
|
|
752
|
+
|
|
753
|
+
`maxAge` is in seconds. This is off by default.
|
|
754
|
+
|
|
755
|
+
`maxBodySize` sets the largest response, in bytes, to cache. The default is 8 MiB (`8 * 1024 * 1024`). A larger response is served from storage each time:
|
|
756
|
+
|
|
757
|
+
```js
|
|
758
|
+
publisherServer.setResponseCache({ maxAge: 3600, maxBodySize: 16 * 1024 * 1024 });
|
|
759
|
+
```
|
|
760
|
+
|
|
761
|
+
- A response is cached by the publish ID, the collection, the path, and the client's `Accept-Encoding`. A cache hit does not read the settings, the index, or the file.
|
|
762
|
+
- A path that does not match a file is cached, too, so a missing path does not read the index again.
|
|
763
|
+
- If several requests miss the same response at the same time, one request produces it, and the others wait for it.
|
|
764
|
+
- Only `200` and `404` responses are cached. Conditional requests (`304`) and `HEAD` requests are answered from the cached response.
|
|
765
|
+
- Each cached response has the surrogate key `<publishId>-<collectionName>`. After you publish, `publish-content` purges this key (see [`--fastly-service-id`](#publish-content)), so the next request gets the new content.
|
|
766
|
+
|
|
767
|
+
`serveRequest()` uses the response cache automatically. If you call `getMatchingAsset()` and `serveAsset()` directly, wrap them in `serveCached()`. When a response is not cached yet, `serveCached()` calls your function to produce it, with a `GET` request that has no conditional headers:
|
|
768
|
+
|
|
769
|
+
```js
|
|
770
|
+
publisherServer.beginRequest(request);
|
|
771
|
+
const response = await publisherServer.serveCached(request, pathname, async (fillRequest) => {
|
|
772
|
+
const asset = await publisherServer.getMatchingAsset(pathname);
|
|
773
|
+
if (asset == null) {
|
|
774
|
+
return null; // not found; this result is cached, too
|
|
775
|
+
}
|
|
776
|
+
return publisherServer.serveAsset(fillRequest, asset);
|
|
777
|
+
});
|
|
778
|
+
```
|
|
779
|
+
|
|
780
|
+
The second argument identifies the response in the collection. If anything other than the path and `Accept-Encoding` changes your response, include it in this value.
|
|
781
|
+
|
|
782
|
+
Notes:
|
|
783
|
+
|
|
784
|
+
- A response is read completely before it is cached, so a request uses memory for one response, up to `maxBodySize`. Other requests that wait for the same response get it when it is cached.
|
|
785
|
+
- A response is cached only if its body has the size in the file's metadata. If storage returns a different body, nothing is cached, the request gets an error, and the next request reads the file again.
|
|
786
|
+
- With `--local`, `publish-content` cannot purge the local cache. Restart `fastly compute serve` to see newly published content, or leave the response cache off in local development.
|
|
787
|
+
- On staging, a purge must include the `Fastly-Purge-Environment: staging` header to clear the staging cache. Without it, a purge clears only the production cache. Use `publish-content --purge-environment=production,staging` to purge both.
|
|
788
|
+
|
|
789
|
+
## ๐ฅ Using Published Assets in Your Code
|
|
790
|
+
|
|
791
|
+
To access files you've published, use the `getMatchingAsset()` and `loadAssetVariant()` methods on `publisherServer`.
|
|
792
|
+
|
|
793
|
+
### Access Metadata for a File:
|
|
794
|
+
|
|
795
|
+
```js
|
|
796
|
+
const asset = await publisherServer.getMatchingAsset('/index.html');
|
|
797
|
+
if (asset != null) {
|
|
798
|
+
// Asset exists with that path
|
|
799
|
+
asset.contentType; // e.g., 'text/html'
|
|
800
|
+
asset.lastModifiedTime; // Unix timestamp
|
|
801
|
+
asset.size; // Size in bytes of the base version
|
|
802
|
+
asset.hash; // SHA256 hash of base version
|
|
803
|
+
asset.variants; // Available variants (e.g., ['gzip'])
|
|
804
|
+
}
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
### Load the File from KV Store:
|
|
808
|
+
|
|
809
|
+
```js
|
|
810
|
+
const assetVariant = await publisherServer.loadAssetVariant(asset, null); // pass 'gzip' or 'br' for compressed
|
|
811
|
+
|
|
812
|
+
assetVariant.storageEntry; // Storage entry (type StorageEntry defined in './src/storage/storage-provider.ts')
|
|
813
|
+
assetVariant.size; // Size of the variant
|
|
814
|
+
assetVariant.hash; // SHA256 of the variant
|
|
815
|
+
assetVariant.contentEncoding; // 'gzip', 'br', or null
|
|
816
|
+
assetVariant.numChunks; // Number of chunks (for large files)
|
|
817
|
+
```
|
|
818
|
+
|
|
819
|
+
You can stream `assetVariant.storageEntry.body` directly to a `Response`, or read it using `.text()`, `.json()`, or `.arrayBuffer()` depending on its content type.
|
|
820
|
+
|
|
821
|
+
---
|
|
822
|
+
|
|
823
|
+
## ๐ CLI Reference
|
|
824
|
+
|
|
825
|
+
### Available Commands
|
|
826
|
+
|
|
827
|
+
#### Outside a Compute App Directory
|
|
828
|
+
- `npx @fastly/compute-js-static-publish@latest [options]` - Scaffold a new Compute app
|
|
829
|
+
|
|
830
|
+
#### Inside a Compute App Directory
|
|
831
|
+
- `publish-content` - Publish static files to storage (KV Store or S3-compatible storage) under a named collection
|
|
832
|
+
- `clean` - Delete expired and unreferenced entries in storage
|
|
833
|
+
- `collections list` - List all published collections
|
|
834
|
+
- `collections delete` - Delete a specific collection index
|
|
835
|
+
- `collections promote` - Copy a collection to another name
|
|
836
|
+
- `collections update-expiration` - Modify expiration time for an existing collection
|
|
837
|
+
|
|
838
|
+
### ๐ App Scaffolding
|
|
839
|
+
|
|
840
|
+
Run outside an existing Compute app directory:
|
|
841
|
+
|
|
842
|
+
#### Minimum required options
|
|
843
|
+
|
|
844
|
+
```sh
|
|
845
|
+
# Using KV store storage
|
|
846
|
+
npx @fastly/compute-js-static-publish@latest \
|
|
847
|
+
--root-dir=./public \
|
|
848
|
+
--kv-store-name=<site-content>
|
|
849
|
+
|
|
850
|
+
# Using S3 storage (BETA)
|
|
851
|
+
npx @fastly/compute-js-static-publish@latest \
|
|
852
|
+
--root-dir=./public \
|
|
853
|
+
--storage-mode=s3 \
|
|
854
|
+
--s3-region=<s3 region> \
|
|
855
|
+
--s3-bucket=<bucket name> \
|
|
856
|
+
[--s3-endpoint=<endpoint>]
|
|
857
|
+
```
|
|
858
|
+
|
|
859
|
+
#### Full options list
|
|
860
|
+
|
|
861
|
+
```sh
|
|
862
|
+
npx @fastly/compute-js-static-publish@latest \
|
|
863
|
+
--root-dir=./public \
|
|
864
|
+
{ [--storage-mode=kv-store] --kv-store-name=<site-content> | \
|
|
865
|
+
--storage-mode=s3 --s3-region=<s3 region> --s3-bucket=<bucket name> [--s3-endpoint=<endpoint>] } \
|
|
866
|
+
[--output=./compute-js] \
|
|
867
|
+
[--static-publisher-working-dir=<output>/static-publisher] \
|
|
868
|
+
[--publish-id=<prefix>] \
|
|
869
|
+
[--static-dir=./public/static] \
|
|
870
|
+
[--spa=./public/spa.html] \
|
|
871
|
+
[--not-found-page=./public/404.html] \
|
|
872
|
+
[--auto-index=index.html,index.htm] \
|
|
873
|
+
[--auto-ext=.html,.htm] \
|
|
874
|
+
[--name=my-site] \
|
|
875
|
+
[--description='My Compute static site'] \
|
|
876
|
+
[--author='you@example.com'] \
|
|
877
|
+
[--service-id=your-fastly-service-id]
|
|
878
|
+
```
|
|
879
|
+
|
|
880
|
+
#### Options:
|
|
881
|
+
|
|
882
|
+
**Used to generate the Compute app:**
|
|
883
|
+
- `--storage-mode`: Specifies the storage mode. Must be either `kv-store` or `s3` (default: `kv-store`).
|
|
884
|
+
|
|
885
|
+
If `--storage-mode=kv-store`:
|
|
886
|
+
- `--kv-store-name`: Required. Name of KV Store to use.
|
|
887
|
+
|
|
888
|
+
If `--storage-mode=s3`:
|
|
889
|
+
- `--s3-region`: Required. Region of the S3-compatible bucket.
|
|
890
|
+
- `--s3-bucket`: Required. Name of the S3-compatible bucket.
|
|
891
|
+
- `--s3-endpoint`: Optional. Custom endpoint of the S3-compatible bucket, if necessary.
|
|
892
|
+
|
|
893
|
+
- `--output`: Compute app destination (default: `./compute-js`)
|
|
894
|
+
- `--static-publisher-working-dir`: Directory to hold working files (default: `<output>/static-publisher`).
|
|
895
|
+
- `--name`: Application name to insert into `fastly.toml`
|
|
896
|
+
- `--description`: Application description to insert into `fastly.toml`
|
|
897
|
+
- `--author`: Author to insert into `fastly.toml`
|
|
898
|
+
- `--service-id`: Optional existing Fastly Compute service ID
|
|
899
|
+
|
|
900
|
+
**Used in building config files:**
|
|
901
|
+
- `--root-dir`: Required. Directory of static site content.
|
|
902
|
+
- `--publish-id`: Optional key prefix for KV entries (default: `'default'`).
|
|
903
|
+
- `--public-dir`: **Deprecated.** A future version will remove it. Public files base directory, under `--root-dir` (default: same as `--root-dir`). Files that are under `--root-dir` but not under `--public-dir` are published, but requests cannot get them.
|
|
904
|
+
- `--static-dir`: One or more directories to serve with long cache TTLs.
|
|
905
|
+
- `--spa`: SPA fallback file path, from the current directory (e.g., `./public/spa.html`). The file must exist under `--root-dir`.
|
|
906
|
+
- `--not-found-page`: 404 fallback file path, from the current directory (e.g., `./public/404.html`). The file must exist under `--root-dir`. If you do not set it, the scaffolder uses `404.html` in `--root-dir` if that file exists.
|
|
907
|
+
- `--auto-index`: List of filenames to use as index files.
|
|
908
|
+
- `--auto-ext`: Extensions to try when resolving URLs.
|
|
909
|
+
|
|
910
|
+
### ๐ Inside a Compute App Directory
|
|
911
|
+
|
|
912
|
+
Once you're in the scaffolded Compute app directory (with `static-publish.rc.js` present), you can run these subcommands:
|
|
913
|
+
|
|
914
|
+
#### `publish-content`
|
|
915
|
+
|
|
916
|
+
```sh
|
|
917
|
+
npx @fastly/compute-js-static-publish publish-content \
|
|
918
|
+
[--root-dir=./public] \
|
|
919
|
+
[--collection-name=preview-42] \
|
|
920
|
+
[--config=./publish-content.config.js] \
|
|
921
|
+
[--expires-in=7d | --expires-at=2025-05-01T12:00Z | --expires-never] \
|
|
922
|
+
[--overwrite-existing] \
|
|
923
|
+
[--brotli-quality=<0-11>] \
|
|
924
|
+
[--local] \
|
|
925
|
+
[--fastly-api-token=...] \
|
|
926
|
+
[--fastly-service-id=...] \
|
|
927
|
+
[--purge-environment=production,staging] \
|
|
928
|
+
[--s3-access-key-id=... --s3-secret-access-key=...] \
|
|
929
|
+
[--verbose]
|
|
930
|
+
```
|
|
931
|
+
|
|
932
|
+
Publishes static files from your local root directory into a named collection, in the storage that `static-publish.rc.js` specifies: the Fastly KV Store, S3-compatible storage (BETA), or a local dev directory (`--local`, KV Store mode only).
|
|
933
|
+
|
|
934
|
+
Before it scans your files, the command lists the files that are already in storage. Files that already exist with the same hash are not compressed or uploaded again. With the KV Store, the command uploads the remaining files in batches.
|
|
935
|
+
|
|
936
|
+
After this process is complete, the PublisherServer object in the Compute application will see the updated index of files and updated server settings from the `publish-content.config.js` file.
|
|
937
|
+
|
|
938
|
+
##### Options:
|
|
939
|
+
|
|
940
|
+
- `--collection-name`: Name of the collection to create/update (default: value in `static-publish.rc.js`)
|
|
941
|
+
- `--config`: Path to a config file to configure server behavior for this collection (default: `./publish-content.config.js`)
|
|
942
|
+
- `--root-dir`: Source directory to read files from (overrides value in `publish-content.config.js`)
|
|
943
|
+
- `--overwrite-existing`: Always upload all files, even if they are already in storage. `--kv-overwrite` is an alias.
|
|
944
|
+
- `--brotli-quality`: Brotli quality for the `br` variants, an integer from 0 to 11. Overrides `brotliQuality` in `publish-content.config.js`. This is useful in CI, where the config file is generated at each run.
|
|
945
|
+
- `--fastly-service-id`: The Fastly Service ID to purge after publishing. The command purges the surrogate key `<publishId>-<collectionName>`, so that the service stops serving cached copies of the collection's settings, index, files, and responses (see [response cache](#๏ธ-caching-responses-with-the-core-cache)). If not set, the tool will check:
|
|
946
|
+
- **`FASTLY_SERVICE_ID` environment variable**
|
|
947
|
+
- `service_id` in `fastly.toml`
|
|
948
|
+
|
|
949
|
+
If none is found, the command skips the purge. The purge also needs an API token (see `--fastly-api-token`). With `--local`, there is no purge. If the purge fails, the command shows a warning and completes, because the content is already published.
|
|
950
|
+
- `--purge-environment`: The environments to purge: `production` (the default), `staging`, or both, as a comma-separated list (`--purge-environment=production,staging`). You can also repeat the option. Purge `staging` if you test the collection on a [staged service version](https://www.fastly.com/documentation/guides/getting-started/services/working-with-staging/), because a purge without it does not clear the staging cache. If the service has no staged version, there is nothing to purge in `staging`. The API then gives the same error as for a service ID that is not correct, so the command shows a message for both causes, not a warning.
|
|
951
|
+
- `--verbose`: Verbose mode. When enabled, the command logs a line for each file that the command scans, and for each upload. Without this option, the command logs the progress after each 1,000 files or uploads.
|
|
952
|
+
|
|
953
|
+
**Expiration:**
|
|
954
|
+
|
|
955
|
+
- `--expires-in`: Time-to-live from now (e.g. `1h`, `2d`, `1w`)
|
|
956
|
+
- `--expires-at`: Absolute expiration time (ISO format: `2025-05-01T12:00Z`)
|
|
957
|
+
- `--expires-never`: Collection never expires
|
|
958
|
+
|
|
959
|
+
*At most one of **`--expires-in`**, **`--expires-at`**, or **`--expires-never`** may be specified*
|
|
960
|
+
|
|
961
|
+
**KV Store Options:**
|
|
962
|
+
|
|
963
|
+
- `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
|
|
964
|
+
|
|
965
|
+
- `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
|
|
966
|
+
|
|
967
|
+
**S3 Storage Options (BETA):**
|
|
968
|
+
|
|
969
|
+
- `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
|
|
970
|
+
- `--s3-upload-concurrency`: Number of objects to upload at the same time, from 1 to 256 (default: 64). Each upload keeps its file in memory, so a site with many large files can need a lower value.
|
|
971
|
+
|
|
972
|
+
#### `clean`
|
|
973
|
+
|
|
974
|
+
```sh
|
|
975
|
+
npx @fastly/compute-js-static-publish clean \
|
|
976
|
+
[--delete-expired-collections] \
|
|
977
|
+
[--dry-run]
|
|
978
|
+
```
|
|
979
|
+
|
|
980
|
+
Cleans up expired or unreferenced items in storage (KV Store or S3-compatible storage).
|
|
981
|
+
This can include expired collection indexes and orphaned content assets.
|
|
982
|
+
|
|
983
|
+
##### Options:
|
|
984
|
+
|
|
985
|
+
- `--delete-expired-collections`: If set, expired collection index files will be deleted.
|
|
986
|
+
- `--dry-run`: Show what would be deleted without performing any deletions.
|
|
987
|
+
|
|
988
|
+
**KV Store Options:**
|
|
989
|
+
|
|
990
|
+
- `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
|
|
991
|
+
|
|
992
|
+
- `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
|
|
993
|
+
|
|
994
|
+
**S3 Storage Options (BETA):**
|
|
995
|
+
|
|
996
|
+
- `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
|
|
997
|
+
|
|
998
|
+
#### `collections list`
|
|
999
|
+
|
|
1000
|
+
```sh
|
|
1001
|
+
npx @fastly/compute-js-static-publish collections list
|
|
1002
|
+
```
|
|
1003
|
+
Lists all collections currently published in storage.
|
|
1004
|
+
|
|
1005
|
+
##### Options:
|
|
1006
|
+
|
|
1007
|
+
**KV Store Options:**
|
|
1008
|
+
|
|
1009
|
+
- `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
|
|
1010
|
+
|
|
1011
|
+
- `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
|
|
1012
|
+
|
|
1013
|
+
**S3 Storage Options (BETA):**
|
|
1014
|
+
|
|
1015
|
+
- `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
|
|
1016
|
+
|
|
1017
|
+
#### `collections promote`
|
|
1018
|
+
|
|
1019
|
+
```sh
|
|
1020
|
+
npx @fastly/compute-js-static-publish collections promote \
|
|
1021
|
+
--collection-name=preview-42 \
|
|
1022
|
+
--to=live \
|
|
1023
|
+
[--expires-in=7d | --expires-at=2025-06-01T00:00Z | --expires-never]
|
|
1024
|
+
```
|
|
1025
|
+
Copies an existing collection (content + config) to a new collection name.
|
|
1026
|
+
|
|
1027
|
+
##### Options:
|
|
1028
|
+
|
|
1029
|
+
- `--collection-name`: The name of the source collection to promote (required)
|
|
1030
|
+
- `--to`: The name of the new (target) collection to create or overwrite (required)
|
|
1031
|
+
|
|
1032
|
+
**Expiration:**
|
|
1033
|
+
|
|
1034
|
+
- `--expires-in`: Time-to-live from now (e.g. `1h`, `2d`, `1w`)
|
|
1035
|
+
- `--expires-at`: Absolute expiration time (ISO format)
|
|
1036
|
+
- `--expires-never`: Collection never expires
|
|
1037
|
+
|
|
1038
|
+
*At most one of **`--expires-in`**, **`--expires-at`**, or **`--expires-never`** may be specified*. If not provided, then the existing expiration rule of the collection being promoted is used.
|
|
1039
|
+
|
|
1040
|
+
**KV Store Options:**
|
|
1041
|
+
|
|
1042
|
+
- `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
|
|
1043
|
+
|
|
1044
|
+
- `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
|
|
1045
|
+
|
|
1046
|
+
**S3 Storage Options (BETA):**
|
|
1047
|
+
|
|
1048
|
+
- `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
|
|
1049
|
+
|
|
1050
|
+
#### `collections update-expiration`
|
|
1051
|
+
|
|
1052
|
+
```sh
|
|
1053
|
+
npx @fastly/compute-js-static-publish collections update-expiration \
|
|
1054
|
+
--collection-name=preview-42 \
|
|
1055
|
+
--expires-in=3d | --expires-at=2025-06-01T00:00Z | --expires-never
|
|
1056
|
+
```
|
|
1057
|
+
Sets or updates the expiration time of an existing collection.
|
|
1058
|
+
|
|
1059
|
+
##### Options:
|
|
1060
|
+
- `--collection-name`: The name of the collection to update (required)
|
|
1061
|
+
|
|
1062
|
+
**Expiration:**
|
|
1063
|
+
|
|
1064
|
+
- `--expires-in`: Time-to-live from now (e.g. `1h`, `2d`, `1w`)
|
|
1065
|
+
- `--expires-at`: Absolute expiration time (ISO format)
|
|
1066
|
+
- `--expires-never`: Collection never expires
|
|
1067
|
+
|
|
1068
|
+
*Exactly one of **`--expires-in`**, **`--expires-at`**, or **`--expires-never`** must be specified*
|
|
1069
|
+
|
|
1070
|
+
**KV Store Options:**
|
|
1071
|
+
|
|
1072
|
+
- `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
|
|
1073
|
+
|
|
1074
|
+
- `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
|
|
1075
|
+
|
|
1076
|
+
**S3 Storage Options (BETA):**
|
|
1077
|
+
|
|
1078
|
+
- `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
|
|
1079
|
+
|
|
1080
|
+
#### `collections delete`
|
|
1081
|
+
|
|
1082
|
+
```sh
|
|
1083
|
+
npx @fastly/compute-js-static-publish collections delete \
|
|
1084
|
+
--collection-name=preview-42
|
|
1085
|
+
```
|
|
1086
|
+
|
|
1087
|
+
Deletes a collection index from storage. The content files will remain as they may still be referenced by other collection indexes.
|
|
1088
|
+
|
|
1089
|
+
Use the `npx @fastly/compute-js-static-publish clean` command afterward to remove content files that are no longer referenced by any collection.
|
|
1090
|
+
|
|
1091
|
+
If a Service ID is found, the command then purges the surrogate key `<publishId>-<collectionName>`, so that the service stops serving cached responses of the deleted collection. This uses the same options as [`publish-content`](#publish-content).
|
|
1092
|
+
|
|
1093
|
+
##### Options:
|
|
1094
|
+
|
|
1095
|
+
- `--collection-name`: The name of the collection to delete (required)
|
|
1096
|
+
|
|
1097
|
+
- `--fastly-service-id`: The Fastly Service ID to purge after deleting. If not set, the tool checks the `FASTLY_SERVICE_ID` environment variable, then `service_id` in `fastly.toml`. If none is found, the command skips the purge. The purge also needs an API token (see `--fastly-api-token`). With `--local`, there is no purge. If the purge fails, the command shows a warning and completes, because the collection is already deleted.
|
|
1098
|
+
|
|
1099
|
+
- `--purge-environment`: The environments to purge: `production` (the default), `staging`, or both, as a comma-separated list. You can also repeat the option.
|
|
1100
|
+
|
|
1101
|
+
**KV Store Options:**
|
|
1102
|
+
|
|
1103
|
+
- `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
|
|
1104
|
+
|
|
1105
|
+
- `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
|
|
1106
|
+
|
|
1107
|
+
**S3 Storage Options (BETA):**
|
|
1108
|
+
|
|
1109
|
+
- `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
|
|
1110
|
+
|
|
1111
|
+
---
|
|
1112
|
+
|
|
1113
|
+
## ๐ Appendix
|
|
1114
|
+
|
|
1115
|
+
### fromCookie
|
|
1116
|
+
|
|
1117
|
+
`collectionSelector.fromCookie` is a utility function that enables the use of a browser
|
|
1118
|
+
cookie to select the active collection.
|
|
1119
|
+
|
|
1120
|
+
```js
|
|
1121
|
+
import { collectionSelector } from '@fastly/compute-js-static-publish';
|
|
1122
|
+
|
|
1123
|
+
const { collectionName, redirectResponse } =
|
|
1124
|
+
collectionSelector.fromCookie(request, {
|
|
1125
|
+
// Everything here is optional โ these are just examples
|
|
1126
|
+
cookieName: 'publisher-collection', // default
|
|
1127
|
+
activatePath: '/activate', // default
|
|
1128
|
+
resetPath: '/reset', // default
|
|
1129
|
+
cookieHttpOnly: true, // default
|
|
1130
|
+
cookieMaxAge: 60 * 60 * 24 * 7, // 7-days. default is `null`, never expires.
|
|
1131
|
+
cookiePath: '/', // default
|
|
1132
|
+
});
|
|
1133
|
+
|
|
1134
|
+
if (redirectResponse) {
|
|
1135
|
+
// honor the redirect
|
|
1136
|
+
return redirectResponse;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
// `collectionName` now holds the active collection (or `null` if none)
|
|
1140
|
+
```
|
|
1141
|
+
|
|
1142
|
+
#### What it does, in plain English
|
|
1143
|
+
|
|
1144
|
+
1. Reads a cookie
|
|
1145
|
+
|
|
1146
|
+
It looks for a cookie named cookieName (default `publisher-collection`) and hands you the value as `collectionName`.
|
|
1147
|
+
|
|
1148
|
+
2. Handles two helper endpoints for you
|
|
1149
|
+
|
|
1150
|
+
| Endpoint | Purpose | Query params | Result |
|
|
1151
|
+
|------------------------------------|------------------|------------------------------------------------------------------------------------------------|-------------------------------------------|
|
|
1152
|
+
| activatePath (default `/activate`) | Set the cookie | `collection` (required) - name of the collection<br /> `redirectTo` (optional, `/` by default) | `302` redirect with a `Set-Cookie` header |
|
|
1153
|
+
| resetPath (default `/reset`) | Clear the cookie | `redirectTo` (optional, `/` by default) | `302` redirect that expires the cookie |
|
|
1154
|
+
|
|
1155
|
+
If a visitor accesses `/activate?collection=blue&redirectTo=/preview`, the helper will issue a redirect and drop `publisher-collection=blue` into their cookie jar.
|
|
1156
|
+
- If someone forgets `?collection=?`? Then `/activate` replies with HTTP `400`.
|
|
1157
|
+
|
|
1158
|
+
When the visitor hits `/reset`, the cookie is deleted.
|
|
1159
|
+
|
|
1160
|
+
3. Safety flags are baked in
|
|
1161
|
+
|
|
1162
|
+
- `HttpOnly` is on by default (configurable), to help avoid XSS issues.
|
|
1163
|
+
- `Secure` is automatically added on HTTPS requests.
|
|
1164
|
+
- `SameSite=Lax` is always set โ reasonable default for previews.
|
|
1165
|
+
|
|
1166
|
+
#### Option reference
|
|
1167
|
+
|
|
1168
|
+
| Option | Type | Default | Notes |
|
|
1169
|
+
|------------------|-------------------|--------------------------|------------------------------------------------|
|
|
1170
|
+
| `cookieName` | string | `'publisher-collection'` | Name of the cookie to read/write |
|
|
1171
|
+
| `activatePath` | string | `'/activate'` | Path that sets the cookie |
|
|
1172
|
+
| `resetPath` | string | `'/reset'` | Path that clears the cookie |
|
|
1173
|
+
| `cookieHttpOnly` | boolean | `true` | Turn off if the client-side needs to read it |
|
|
1174
|
+
| `cookieMaxAge` | number\|undefined | `undefined` | Seconds until expiry; omit for session cookies |
|
|
1175
|
+
| `cookiePath` | string | `'/'` | Path attribute in the cookie |
|
|
1176
|
+
|
|
1177
|
+
#### Example
|
|
1178
|
+
|
|
1179
|
+
`fromCookie` can be dropped into a Fastly Compute app:
|
|
1180
|
+
|
|
1181
|
+
```js
|
|
1182
|
+
async function handleRequest(event) {
|
|
1183
|
+
const request = event.request;
|
|
1184
|
+
|
|
1185
|
+
// --- Cookie handling starts here
|
|
1186
|
+
const { collectionName, redirectResponse } = collectionSelector.fromCookie(request);
|
|
1187
|
+
if (redirectResponse) {
|
|
1188
|
+
// obey redirect first
|
|
1189
|
+
return redirectResponse;
|
|
1190
|
+
}
|
|
1191
|
+
publisherServer.setActiveCollectionName(collectionName); // null selects the default collection
|
|
1192
|
+
// --- Cookie handling ends here
|
|
1193
|
+
|
|
1194
|
+
// Regular routing follows...
|
|
1195
|
+
const response = await publisherServer.serveRequest(request);
|
|
1196
|
+
if (response != null) {
|
|
1197
|
+
return response;
|
|
1198
|
+
}
|
|
1199
|
+
return new Response('Not found', { status: 404 });
|
|
1200
|
+
}
|
|
1201
|
+
```
|
|
1202
|
+
|
|
1203
|
+
---
|
|
1204
|
+
|
|
1205
|
+
## ๐ Next Steps
|
|
1206
|
+
|
|
1207
|
+
- View CLI command help: `npx @fastly/compute-js-static-publish --help`
|
|
1208
|
+
- Use in CI to automate branch previews
|
|
1209
|
+
- Visit [https://developer.fastly.com](https://developer.fastly.com) for Compute platform docs
|
|
1210
|
+
|
|
1211
|
+
## Development
|
|
1212
|
+
|
|
1213
|
+
To build the package, run `npm run build`. To run the tests, see [test/README.md](./test/README.md).
|
|
1214
|
+
|
|
1215
|
+
## Issues
|
|
1216
|
+
|
|
1217
|
+
If you encounter any non-security-related bug or unexpected behavior, please [file an issue][bug] using the bug report template.
|
|
1218
|
+
|
|
1219
|
+
[bug]: https://github.com/fastly/compute-js-static-publish/issues/new?labels=bug
|
|
1220
|
+
|
|
1221
|
+
### Security issues
|
|
1222
|
+
|
|
1223
|
+
Please see our [SECURITY.md](SECURITY.md) for guidance on reporting security-related issues.
|
|
1224
|
+
|
|
1225
|
+
## License
|
|
1226
|
+
|
|
1227
|
+
[MIT](./LICENSE).
|