What is `storage` and how to use it for request-scoped data
canaryThe storage object is a shared data repository accessible to all functions within a single request chain. It is designed to prevent redundant data fetching (e.g., fetching a user profile multiple times) by allowing you to fetch data once and store it for subsequent middleware or functions to consume.
Key Characteristics:
- Request Scoped: Each request receives its own instance of
event, meaningstoragecontent does not persist between different requests. - Default Implementation: By default,
storageuses an in-memory implementation. - Performance Warning: If you implement a custom adapter that queries an external database, every request to that adapter will increase the Time to First Byte (TTFB). It is highly recommended to use key-value stores like Redis or Vercel Edge Config for custom adapters.
import type { NextMiddleware } from "@zanreal/nemo";
const example: NextMiddleware = async (req, { storage }) => {
let user = undefined;
if (!storage.has("user")) {
user = await fetchUser();
storage.set("user", user);
} else {
user = storage.get("user");
}
if (!user) {
return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
}
};