future.unstable_middleware
flag.
Creates a type-safe context object that can be used to store and retrieve values in middleware, loaders, and actions. Similar to React's createContext
, but designed for React Router's request/response lifecycle.
unstable_createContext<T>(defaultValue?: T): RouterContext<T>
An optional default value for the context. This value will be returned if no value has been set for this context.
A RouterContext<T>
object that can be used with context.get()
and context.set()
in middleware, loaders, and actions.
import { unstable_createContext } from "react-router";
// Create a context for user data
export const userContext =
unstable_createContext<User | null>(null);
import { userContext } from "~/context";
import { getUserFromSession } from "~/auth.server";
export const authMiddleware = async ({
request,
context,
}) => {
const user = await getUserFromSession(request);
context.set(userContext, user);
};
import { userContext } from "~/context";
export async function loader({
context,
}: Route.LoaderArgs) {
const user = context.get(userContext);
if (!user) {
throw new Response("Unauthorized", { status: 401 });
}
return { user };
}