We landed our initial unstable implementation of middleware behind a future flag in 7.3.0. Since then, we’ve been iterating on the API/implementation and working closely with community members who adopted the unstable flag for alpha testing. We received a ton of valuable feedback from those folks that helped us move the API to an even better spot in the end.
We’re excited to finally stabilize these APIs in 7.9.0 behind the
future.v8_middleware
flag and can’t wait to see the interesting patterns folks come up with when using them. There are already a handful of useful middlewares available in remix-utils that are worth checking out!
Providing data from a parent to a child:
// app/root.tsx
const context = createContext<User>();
const userMiddleware: Route.MiddlewareFunction = ({ context }) => {
let user = await getUser(request);
context.set(userContext, user); // 👈 Provide data here
};
export const middleware = [userMiddleware];
export async function loader({ context }) {
return { user: context.get(userContext) }; // 👈 Access data here
}
// app/routes/_index.tsx
export async function loader({ request }) {
let user = context.get(userContext); // 👈 Access data here
// ...
}
Short-circuiting child loaders with a redirect:
// app/routes/_auth.tsx
const requireUserMiddleware: Route.MiddlewareFunction = ({ context }) => {
let user = await getUser(request);
if (!user) {
throw redirect("/login");
}
// ...
};
export const middleware = [requireUserMiddleware];
// app/routes/_auth.profile.tsx
export async function loader({ request }) {
// ✅ This code will never run if there's no logged-in user
let data = await getUserData(request);
return data;
}
Leave a Reply