remix-utils
Version:
This package contains simple utility functions to use with [React Router](https://reactrouter.com/).
56 lines • 2.23 kB
JavaScript
import { AsyncLocalStorage } from "node:async_hooks";
const storage = new AsyncLocalStorage();
/**
* Creates a context storage middleware that stores the context, and request,
* in an AsyncLocalStorage.
*
* This is useful for accessing the context in any part of the application
* inside loaders or actions, but without needing to pass the context around
* from loaders or actions to those functions.
*
* After the middleware is added, any function that needs the context can
* call the `getContext` function to retrieve the context from the storage.
*
* @returns The context storage middleware and a function to get the context from the storage
* @example
* // app/middlewares/context-storage.ts
* import { unstable_createContextStorageMiddleware } from "remix-utils";
*
* export const [contextStorageMiddleware, getContext, getRequest] = unstable_createContextStorageMiddleware();
*
* // app/root.tsx
* import { contextStorageMiddleware } from "~/middlewares/context-storage";
* export const unstable_middleware = [contextStorageMiddleware];
*
* // app/helpers/authenticate.ts
* import { getContext } from "~/middlewares/context-storage";
* import { getSession } from "~/middlewares/session";
*
* export function authenticate() {
* let context = getContext();
* let session = getSession(context);
* // code to authenticate the user
* }
*/
export function unstable_createContextStorageMiddleware() {
return [
async function contextStorageMiddleware({ request, context }, next) {
return storage.run({ request, context }, next);
},
function getContext() {
let store = storage.getStore();
if (!store) {
throw new Error("Failed to retrieve context from storage. Did you forget to use the contextStorageMiddleware?");
}
return store.context;
},
function getRequest() {
let store = storage.getStore();
if (!store) {
throw new Error("Failed to retrieve request from storage. Did you forget to use the contextStorageMiddleware?");
}
return store.request;
},
];
}
//# sourceMappingURL=context-storage.js.map