Better Way to Fetch Secrets from Wix Secret Manager - Tutorial

When building a website or a web application most of the times we store some sensitive things that shouldn’t be exposed to users, and this is when we use “Secret Managers”. Thankfully Wix has it’s built-in secret manager where we can store API keys, connection strings etc.

When you fetch a secret from Wix’s secret manager it needs to go to a server, get the secret, and come back which usually takes around 200-400ms on average.

And you wouldn’t want to slow down your API requests to other services by adding extra delay because of secret fetch on every request. This is where caching comes into play.

If we cache responses of requests we are making we can make the next request/s much more faster.

Wix Secret Manager benchmark here: https://exweiv.wixstudio.com/wix-secret-benchmark

*refresh page and see caching in effect

How Caching Works in Wix?

Wix site backends runs inside container/s, and each container instance has limited amount of compute power (vCPU and RAM). Let’s say we have Basic plan it means that we will have 400MB RAM in our backend container.

When we fetch a secret and get the response from server we can save it to memory (RAM) and next time we need to fetch the exact same secret we can get it from the memory instead of making a new request.

This will make things much faster because it’ll directly remove the network delay and since we store it inside memory which is much faster than disk we will get it even less than a millisecond.

Until that point there isn’t specific to Wix, it’s just how caching in memory works. Like how Redis stores data.

But Wix backend containers has some lifespan and unlike us, humans they don’t live for years instead they have maximum of 6 minutes and then they are just gone.

So our cache can stay there maximum of 6 minutes, just keep this in mind.

How to Cache Secrets

To make things easier we have created an NPM package for you to both cache secret requests, parse JSON based strings, and enable/disable access elevation.

https://www.npmjs.com/package/@exweiv/wix-secret-helpers

Retrieve a Secret as a String

import { getSecretValue } from '@exweiv/wix-secret-helpers';

// Returns `string`
const weatherAPIKey = await getSecretValue({ secretName: "WeatherAPIKey" }); 
const client = new WeatherClient(weatherAPIKey);

Retrieve and Parse a JSON Secret

import { getSecretValue } from '@exweiv/wix-secret-helpers';

// Returns defined `object`
/** @type {{appKey: string, appSecret: string, accessToken: string, accessSecret: string}} */
const twitterAPIConfig = await getSecretValue({ secretName: "TwitterJSON", parseJSON: true });
const client = new TwitterAPI(twitterAPIConfig);

Notes: caching is enabled by default but you can disable it, secrets are returned as string unless you enable JSON parsing, all requests are elevated by default unless you disable it.

Read more in GitHub or NPM.


3 Likes