Options
All
  • Public
  • Public/Protected
  • All
Menu

Interface BrowserCacheOptions

Options for controlling caching behavior in the browser

Hierarchy

  • BrowserCacheOptions

Index

Properties

Optional convertToGet

convertToGet: undefined | false | true

Set to true to convert all requests to GETs using the service worker. Doing so allows you to prefetch and cache non-GET requests. Since all prefetch requests are GETs, setting this config to true will ensure that the actual, non-prefetch requests use GET as well and thus have the same cache key as their prefetch counterparts.

When true, the service worker will add the request body as the pref_layer0_body parameter. You can then use a .get() route with transformRequest to convert the get to the original method (post, for example) when fetching from the backend.

Note that you must specify two routes when using this method: one for the get and one for the original method, This is because do not guarantee that the service worker is installed and running by the time requests are sent, so some requests will inevitably sent using their original method and body.

Example

 import { Router } from '@layer0/core/router'
 import { transformMethod } from '@layer0/core/transform'

 const cacheConfig = {
   edge: {
     maxAgeSeconds: 60 * 60 * 24,
     staleWhileRevalidateSeconds: 60 * 60
   },
   browser: {
     serviceWorkerSeconds: 60 * 60 * 24,
     convertToGet: true // convert POSTs to GETs so we can prefetch and cache them
   }
 }

 export default new Router()
   // When the request is a GET, convert it to post using serverless compute and cache the result
   .get('/some-post-path', (res) => {
     res.proxy('origin', {
       transformRequest: transformMethod({
         toMethod: 'post',
         res,
         cache: cacheConfig
       })
     })
   })
   // When the request is a POST, forward it to origin from the edge without using serverless compute
   .post('/some-post-path', ({ cache, proxy }) => {
     cache(cacheConfig)
     proxy('origin')
   })
param

The method to to set

Optional maxAgeSeconds

maxAgeSeconds: undefined | number

Sets the max-age value of the cache-control header sent to the browser. This controls the duration that the response is held in the browser's http cache.

Optional serviceWorkerSeconds

serviceWorkerSeconds: undefined | number

Sends an x-sw-cache-control header with a value of max-age={serviceWorkerSeconds}. This is not a standard header that service workers understand by default. You'll need to implement logic to handle this in your service worker.

Generated using TypeDoc