Skip to content

docs: Add some docs for unstable middleware #13930

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions docs/api/utils/createContext.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
---
title: createContext
unstable: true
---

# unstable_createContext

[MODES: framework, data]

<br/>
<br/>

<docs-warning>This API is experimental and subject to breaking changes. Enable it with the `future.unstable_middleware` flag.</docs-warning>

## Summary

[Reference Documentation ↗](https://api.reactrouter.com/v7/functions/react_router.unstable_createContext.html)

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.

## Signature

```tsx
unstable_createContext<T>(defaultValue?: T): RouterContext<T>
```

## Params

### defaultValue

An optional default value for the context. This value will be returned if no value has been set for this context.

## Returns

A `RouterContext<T>` object that can be used with `context.get()` and `context.set()` in middleware, loaders, and actions.

## Examples

### Basic Usage

```tsx filename=app/context.ts
import { unstable_createContext } from "react-router";

// Create a context for user data
export const userContext =
unstable_createContext<User | null>(null);
```

```tsx filename=app/middleware/auth.ts
import { userContext } from "~/context";
import { getUserFromSession } from "~/auth.server";

export const authMiddleware = async ({
request,
context,
}) => {
const user = await getUserFromSession(request);
context.set(userContext, user);
};
```

```tsx filename=app/routes/profile.tsx
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 };
}
```

## See Also

- [Middleware Guide](../../how-to/middleware)
Loading