Implement a custom value serializer for Redis
masterBy default, the redis-strings handler uses JSON.stringify and JSON.parse. You can provide a custom valueSerializer object to implement compression (e.g., gzip, brotli) or encryption.
Contract:
serialize(value): Receives the full cache object (includingtags,lastModified,lifespan, andvalue). Must return a string suitable for RedisSET.deserialize(stored): Receives the string from RedisGET. Must return a parsed object compatible with the handler, ornullto trigger a cache miss.
Note: Changing the serializer makes existing keys unreadable. You must flush the cache or use a new keyPrefix when deploying a change to the serializer.
// Example: gzip compression
import createRedisHandler from "@fortedigital/nextjs-cache-handler/redis-strings";
import { gzipSync, gunzipSync } from "zlib";
const redisCacheHandler = createRedisHandler({
client: redisClient,
keyPrefix: "nextjs:",
valueSerializer: {
serialize: (value) => gzipSync(JSON.stringify(value)).toString("base64"),
deserialize: (stored) => {
const parsed = JSON.parse(
gunzipSync(Buffer.from(stored, "base64")).toString("utf-8"),
);
return parsed;
},
},
});