Nitro, the server that Nuxt 3 uses, comes with a very powerful key-value storage system:
const storage = useStorage();// Save a valueawait storage.setItem('some:key', value);// Retrieve a valueconst item = await storage.getItem('some:key');
It’s not a replacement for a robust database, but it’s perfect for temporary data or a caching layer.
One great application of this “session storage” is using it during an OAuth flow.
In the first step of the flow, we receive a state
and a codeVerifier
. In the second step, we receive a code
along with the state
again, which let’s us use the codeVerifier
to verify that the code
is authentic.
We need to store the codeVerifier
in between these steps, but only for a few minutes — perfect for Nitro’s storage!
The first step in the /oauth
endpoint we store the codeVerifier
:
// ~/server/api/oauth// ...const storage = useStorage();const key = `verifier:${state}`;await storage.setItem(key, codeVerifier);// ...
Then we retrieve it during the second step in the /callback
endpoint:
// ~/server/api/callback// ...const storage = useStorage();const key = `verifier:${state}`;const codeVerifier = await storage.getItem(key);// ...
A simple and easy solution, with no need to add a new table to our database and deal with an extra migration.
This just scratches the surface. Learn more about the unstorage
package that powers this: https://github.com/unjs/unstorage