Skip to content

Commit 5f71b74

Browse files
authored
docs(cache): add note on cache key normalization and escapeKey usage (#632)
1 parent b3709d9 commit 5f71b74

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

docs/content/docs/2.features/cache.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,51 @@ await useStorage('cache').clear('nitro:handlers')
152152
Read more about Nitro Cache.
153153
::
154154

155+
### Normalizing Cache Keys
156+
157+
::important
158+
**Cache keys are automatically normalized** using an internal utility that removes non-alphanumeric characters such as `/` and `-`. This behavior helps ensure compatibility across various storage backends (e.g., `file systems`, `key-value` stores) that might have restrictions on characters in `keys`, and also prevents potential path traversal vulnerabilities.
159+
::
160+
161+
For example:
162+
163+
```ts
164+
getKey: () => '/api/products/sale-items'
165+
```
166+
167+
Would generate a key like:
168+
169+
```ts
170+
api/productssaleitems.json
171+
```
172+
173+
This behavior may result in keys that look different from the original route or identifier.
174+
175+
::tip
176+
To manually reproduce the same normalized key pattern used by Nitro (e.g., when invalidating cache entries), you can use the `escapeKey` utility function provided below:
177+
::
178+
179+
```ts
180+
function escapeKey(key: string | string[]) {
181+
return String(key).replace(/\W/g, "");
182+
}
183+
```
184+
185+
It's recommended to use `escapeKey()` when invalidating manually using route paths or identifiers to ensure consistency with Nitro's internal key generation.
186+
187+
For example, if your `getKey` function is:
188+
189+
```ts
190+
getKey: (id: string) => `product/${id}/details`
191+
```
192+
193+
And you want to invalidate `product/123/details`, you would do:
194+
195+
```ts
196+
const normalizedKey = escapeKey('product/123/details')
197+
await useStorage('cache').removeItem(`nitro:functions:getProductDetails:${normalizedKey}.json`)
198+
```
199+
155200
## Cache Expiration
156201

157202
As NuxtHub leverages Cloudflare Workers KV to store your cache entries, we leverage the [`expiration` property](https://developers.cloudflare.com/kv/api/write-key-value-pairs/#expiring-keys) of the KV binding to handle the cache expiration.

0 commit comments

Comments
 (0)