Router caching in an effective strategy to improve your site's performance by temporarily storing the return values from the ok()
method, which contain the same page data that is sent as the response to a router request. When visitors access a router page, the system can quickly deliver the cached data, enabling faster page loads and a better overall user experience. This article guides you through the process of implementing router caching and how to invalidate it when necessary.
You must assign identifiers to router caches and can optionally define a cache's Time To Live (TTL). These required identifiers, called tags, allow you to easily identify caches that may need invalidation. For example, you can invalidate all caches that have the tag "dress-page."
To set up caching for your routers:
Open the router.js file in your backend code and find the routers you want to cache.
In the request for each router page you want to cache, create a variable representing the options
parameter to store the cache
object. Include the following fields in the cache
object:
tags
: One or more identifiers of the cached return value.ttl
: The cache's time-to-live in seconds. If omitted, defaults to 1 week (604800
seconds).In the return statement of the router request, pass the variable holding the cache
object to the ok()
method.
Important:
The tags
field is required for caching. If you omit tags
, nothing is cached.
Invalidating or clearing your caches triggers the routing and rendering process upon the following next, ensuring that your caches hold the most up-to-date page data.
To invalidate caches, use the invalidateCache()
method from the wix-cache-backend
module. This method accepts the invalidationMethods
parameter, which specifies the tags previously assigned to the caches you want to invalidate.
Important:
invalidationMethods
when invalidating your cache.invalidationMethods
object will be invalidated when invalidateCache()
is called.invalidateCache()
method must be elevated and wrapped in a web method.To invalidate caches:
Add the necessary imports in your backend files.
Create a variable to store the tags assigned to the cache. Then call elevate()
and store its returned value in another variable.
Call webMethod()
and store its return value in an exported variable. Pass a permissions value and the elevated invalidation method.
Notes:
wix-cache-backend
API, allows you to invalidate web method caches as well as router caches.invalidateCache()
method in the wix-site-backend
module.