react-router)@react-router/*)This page lists all releases/release notes for React Router back to v6.0.0. For releases prior to v6, please refer to the Github Releases Page.
We manage release notes in this file instead of the paginated Github Releases Page for 2 reasons:
Date: 2025-10-08
useRoute() (unstable)This release includes a new unstable_useRoute() hook that provides a type-safe way to access route loaderData/actionData from a specific route in Framework Mode. Think if it like a better version of useRouteLoaderData that works with the typegen system and also supports actionData. Check out the changelog entry below for more information.
@react-router/dev - Update valibot dependency to ^1.1.0 (#14379)@react-router/node - Validate format of incoming session ids (#14426)⚠️ Unstable features are not recommended for production use
react-router - handle external redirects in from server actions (#14400)
react-router - New (unstable) useRoute hook for accessing data from specific routes (#14407)
For example, let's say you have an admin route somewhere in your app and you want any child routes of admin to all have access to the loaderData and actionData from admin.
// app/routes/admin.tsx
import { Outlet } from "react-router";
export const loader = () => ({ message: "Hello, loader!" });
export const action = () => ({ count: 1 });
export default function Component() {
return (
<div>
{/* ... */}
<Outlet />
{/* ... */}
</div>
);
}
You might even want to create a reusable widget that all of the routes nested under admin could use:
import { unstable_useRoute as useRoute } from "react-router";
export function AdminWidget() {
// How to get `message` and `count` from `admin` route?
}
In framework mode, useRoute knows all your app's routes and gives you TS errors when invalid route IDs are passed in:
export function AdminWidget() {
const admin = useRoute("routes/dmin");
// ^^^^^^^^^^^
}
useRoute returns undefined if the route is not part of the current page:
export function AdminWidget() {
const admin = useRoute("routes/admin");
if (!admin) {
throw new Error(`AdminWidget used outside of "routes/admin"`);
}
}
Note: the root route is the exception since it is guaranteed to be part of the current page.
As a result, useRoute never returns undefined for root.
loaderData and actionData are marked as optional since they could be accessed before the action is triggered or after the loader threw an error:
export function AdminWidget() {
const admin = useRoute("routes/admin");
if (!admin) {
throw new Error(`AdminWidget used outside of "routes/admin"`);
}
const { loaderData, actionData } = admin;
console.log(loaderData);
// ^? { message: string } | undefined
console.log(actionData);
// ^? { count: number } | undefined
}
If instead of a specific route, you wanted access to the current route's loaderData and actionData, you can call useRoute without arguments:
export function AdminWidget() {
const currentRoute = useRoute();
currentRoute.loaderData;
currentRoute.actionData;
}
This usage is equivalent to calling useLoaderData and useActionData, but consolidates all route data access into one hook: useRoute.
Note: when calling useRoute() (without a route ID), TS has no way to know which route is the current route.
As a result, loaderData and actionData are typed as unknown.
If you want more type-safety, you can either narrow the type yourself with something like zod or you can refactor your app to pass down typed props to your AdminWidget:
export function AdminWidget({
message,
count,
}: {
message: string;
count: number;
}) {
/* ... */
}
Full Changelog: v7.9.3...v7.9.4
Date: 2025-09-26
react-router - Fix Data Mode regression causing a 404 during initial load in when middleware exists without any loader functions (#14393)react-router - Do not try to use turbo-stream to decode CDN errors that never reached the server (#14385)
ErrorBoundary instead of a generic "Unable to decode turbo-stream response" errorFull Changelog: v7.9.2...v7.9.3
Date: 2025-09-24
This release contains a handful of bug fixes, but we think you'll be most excited about the new unstable stuff 😉.
This release includes our first release of unstable support for RSC in Framework Mode! You can read more about it in our blog post and the docs.
This release also includes a new (long-requested) fetcher.unstable_reset() API to reset fetchers back to their initial idle state.
react-router - Ensure client-side router runs client middleware during initialization data load (if required) even if no loaders exist (#14348)react-router - Fix middleware prop not being supported on <Route> when used with a data router via createRoutesFromElements (#14357)react-router - Update createRoutesStub to work with middleware (#14348)
<RoutesStub future={{ v8_middleware: true }} /> flag to enable the proper context typereact-router - Update Lazy Route Discovery manifest requests to use a singular comma-separated paths query param instead of repeated p query params (#14321)
react-router - Fail gracefully on manifest version mismatch logic if sessionStorage access is blocked (#14335)react-router - Update useOutlet returned element to have a stable identity in-between route changes (#13382)react-router - Handle encoded question mark and hash characters in ancestor splat routes (#14249)@react-router/dev - Switch internal vite plugin Response logic to use @remix-run/node-fetch-server (#13927)@react-router/dev - Fix presets future flags being ignored during config resolution (#14369)⚠️ Unstable features are not recommended for production use
react-router - Add fetcher.unstable_reset() API (#14206)react-router - In RSC Data Mode, handle SSR'd client errors and re-try in the browser (#14342)react-router - Enable full transition support for the RSC router (#14362)@react-router/dev - Add unstable support for RSC Framework Mode (#14336)@react-router/serve - Disable compression() middleware in RSC framework mode (#14381)Full Changelog: v7.9.1...v7.9.2
Date: 2025-09-12
Future interface naming from middleware -> v8_middleware (#14327)Full Changelog: v7.9.0...v7.9.1
Date: 2025-09-12
We have removed the unstable_ prefix from the following APIs and they are now considered stable and ready for production use:
RouterContextProvidercreateContextcreateBrowserRouter getContext option<HydratedRouter> getContext propPlease see the Middleware Docs, the Middleware RFC, and the Client-side Context RFC for more information.
react-router - Update href() to correctly process routes that have an extension after the parameter or are a single optional parameter (#13797)react-router - Escape HTML in meta() JSON-LD content (#14316)⚠️ Unstable features are not recommended for production use
react-router - RSC: Add react-server Await component implementation (#14261)react-router - RSC: Fix hydration errors for routes that only have client loaders when using RSC in Data Mode along with a custom basename (#14264)react-router - RSC: Make href function available in a react-server context (#14262)react-router - RSC: Decode each time getPayload() is called to allow for "in-context" decoding and hoisting of contextual assets (#14248)Full Changelog: v7.8.2...v7.9.0
Date: 2025-08-22
react-router - Maintain ReadonlyMap and ReadonlySet types in server response data. (#13092)react-router - Fix basename usage without a leading slash in data routers (#11671)react-router - Fix TypeError if you throw from patchRoutesOnNavigation when no partial matches exist (#14198)react-router - Properly escape interpolated param values in generatePath() (#13530)@react-router/dev - Fix potential memory leak in default entry.server (#14200)⚠️ Unstable features are not recommended for production use
Client-side onError
react-router - Add <RouterProvider unstable_onError>/<HydratedRouter unstable_onError> prop for client side error reporting (#14162)Middleware
react-router - Delay serialization of .data redirects to 202 responses until after middleware chain (#14205)react-router - Update client middleware so it returns the dataStrategy results up the chain allowing for more advanced post-processing middleware (#14151, #14212)react-router - Remove Data Mode future.unstable_middleware flag from createBrowserRouter (#14213)
getLoadContext type behavior changeRSC
react-router - Allow opting out of revalidation on server actions with hidden $SKIP_REVALIDATION input (#14154)Full Changelog: v7.8.1...v7.8.2
Date: 2025-08-15
react-router - Fix usage of optional path segments in nested routes defined using absolute paths (#14135)react-router - Fix optional static segment matching in matchPath (#11813)react-router - Fix pre-rendering when a basename is set with ssr:false (#13791)react-router - Properly convert returned/thrown data() values to Response instances via Response.json() in resource routes and middleware (#14159, #14181)@react-router/dev - Update generated Route.MetaArgs type so loaderData is only potentially undefined when an ErrorBoundary export is present (#14173)⚠️ Unstable features are not recommended for production use
Middleware
react-router - Bubble client pre-next middleware errors to the shallowest ancestor that needs to load, not strictly the shallowest ancestor with a loader (#14150)react-router - Propagate non-redirect Response values thrown from middleware to the error boundary on document/data requests (#14182)RSC
react-router - Provide isRouteErrorResponse utility in react-server environments (#14166)react-router - Handle meta and links Route Exports in RSC Data Mode (#14136)Full Changelog: v7.8.0...v7.8.1
Date: 2025-08-07
loaderData valuesEver noticed the discrepancies in loader data values handed to you by the framework? Like, we call it loaderData in your component props, but then match.data in your matches? Yeah, us too - as well as some keen-eyed React Router users who raised this in a proposal. We've added new loaderData fields alongside existing data fields in a few lingering spots to align with the loaderData naming used in the new Route.* APIs.
The biggest set of changes in 7.8.0 are to the unstable_middleware API's as we move closer to stabilizing them. If you've adopted the middleware APIs for early testing, please read the middleware changes below carefully. We hope to stabilize these soon so please let us know of any feedback you have on the API's in their current state!
react-router - Add nonce prop to Links & PrefetchPageLinks (#14048)react-router - Add loaderData arguments/properties alongside existing data arguments/properties to provide consistency and clarity between loaderData and actionData across the board (#14047)
Route.MetaArgs, Route.MetaMatch, MetaArgs, MetaMatch, Route.ComponentProps.matches, UIMatch@deprecated warnings have been added to the existing data properties to point users to new loaderData properties, in preparation for removing the data properties in a future major releasereact-router - Prevent "Did not find corresponding fetcher result" console error when navigating during a fetcher.submit revalidation (#14114)
react-router - Switch Lazy Route Discovery manifest URL generation to use a standalone URLSearchParams instance instead of URL.searchParams to avoid a major performance bottleneck in Chrome (#14084)
react-router - Adjust internal RSC usage of React.use to avoid Webpack compilation errors when using React 18 (#14113)
react-router - Remove dependency on @types/node in TypeScript declaration files (#14059)
react-router - Fix types for UIMatch to reflect that the loaderData/data properties may be undefined (#12206)
When an ErrorBoundary is being rendered, not all active matches will have loader data available, since it may have been their loader that threw to trigger the boundary
The UIMatch.data type was not correctly handing this and would always reflect the presence of data, leading to the unexpected runtime errors when an ErrorBoundary was rendered
⚠️ This may cause some type errors to show up in your code for unguarded match.data accesses - you should properly guard for undefined values in those scenarios.
// app/root.tsx
export function loader() {
someFunctionThatThrows(); // ❌ Throws an Error
return { title: "My Title" };
}
export function Layout({ children }: { children: React.ReactNode }) {
let matches = useMatches();
let rootMatch = matches[0] as UIMatch<Awaited<ReturnType<typeof loader>>>;
// ^ rootMatch.data is currently incorrectly typed here, so TypeScript does
// not complain if you do the following which throws an error at runtime:
let { title } = rootMatch.data; // 💥
return <html>...</html>;
}
@react-router/dev - Fix rename without mkdir in Vite plugin (#14105)
⚠️ Unstable features are not recommended for production use
RSC
react-router - Fix Data Mode issue where routes that return false from shouldRevalidate would be replaced by an <Outlet /> (#14071)react-router - Proxy server action side-effect redirects from actions for document and callServer requests (#14131)Middleware
react-router - Change the unstable_getContext signature on RouterProvider, HydratedRouter, and unstable_RSCHydratedRouter so that it returns an unstable_RouterContextProvider instance instead of a Map used to construct the instance internally (#14097)
unstable_getContext propreact-router - Run client middleware on client navigations even if no loaders exist (#14106)
react-router - Convert internal middleware implementations to use the new unstable_generateMiddlewareResponse API (#14103)
react-router - Ensure resource route errors go through handleError w/middleware enabled (#14078)
react-router - Propagate returned Response from server middleware if next wasn't called (#14093)
react-router - Allow server middlewares to return data() values which will be converted into a Response (#14093, #14128)
react-router - Update middleware error handling so that the next function never throws and instead handles any middleware errors at the proper ErrorBoundary and returns the Response up through the ancestor next function (#14118)
next calls in try/catch you should be able to remove thosereact-router - Bubble client-side middleware errors prior to next to the appropriate ancestor error boundary (#14138)
react-router - When middleware is enabled, make the context parameter read-only (Readonly<unstable_RouterContextProvider>) so that TypeScript will not allow you to write arbitrary fields to it in loaders, actions, or middleware. (#14097)
react-router - Rename and alter the signature/functionality of the unstable_respond API in staticHandler.query/staticHandler.queryRoute (#14103)
This only impacts users using createStaticHandler() for manual data loading during non-Framework Mode SSR
The API has been renamed to unstable_generateMiddlewareResponse for clarity
The main functional change is that instead of running the loaders/actions before calling unstable_respond and handing you the result, we now pass a query/queryRoute function as a parameter and you execute the loaders/actions inside your callback, giving you full access to pre-processing and error handling
The query version of the API now has a signature of (query: (r: Request) => Promise<StaticHandlerContext | Response>) => Promise<Response>
The queryRoute version of the API now has a signature of (queryRoute: (r: Request) => Promise<Response>) => Promise<Response>
This allows for more advanced usages such as running logic before/after calling query and direct error handling of errors thrown from query
⚠️ This is a breaking change if you've adopted the staticHandler unstable_respond API
let response = await staticHandler.query(request, {
requestContext: new unstable_RouterContextProvider(),
async unstable_generateMiddlewareResponse(query) {
try {
// At this point we've run middleware top-down so we need to call the
// handlers and generate the Response to bubble back up the middleware
let result = await query(request);
if (isResponse(result)) {
return result; // Redirects, etc.
}
return await generateHtmlResponse(result);
} catch (error: unknown) {
return generateErrorResponse(error);
}
},
});
@react-router/{architect,cloudflare,express,node} - Change the getLoadContext signature (type GetLoadContextFunction) when future.unstable_middleware is enabled so that it returns an unstable_RouterContextProvider instance instead of a Map used to construct the instance internally (#14097)
type unstable_InitialContext exportgetLoadContext docs for more informationgetLoadContext functioncreate-react-routerreact-router@react-router/architect@react-router/cloudflare@react-router/dev@react-router/express@react-router/fs-routes@react-router/node@react-router/remix-config-routes-adapter@react-router/serveFull Changelog: v7.7.1...v7.8.0
Date: 2025-07-24
@react-router/dev - Update to Prettier v3 for formatting when running react-router reveal --no-typescript (#14049)⚠️ Unstable features are not recommended for production use
react-router - RSC Data Mode: fix bug where routes with errors weren't forced to revalidate when shouldRevalidate returned false (#14026)react-router - RSC Data Mode: fix Matched leaf route at location "/..." does not have an element or Component warnings when error boundaries are rendered (#14021)Full Changelog: v7.7.0...v7.7.1
Date: 2025-07-16
We're excited to introduce experimental support for RSC in Data Mode via the following new APIs:
unstable_RSCHydratedRouterunstable_RSCStaticRouterunstable_createCallServerunstable_getRSCStreamunstable_matchRSCServerRequestunstable_routeRSCServerRequestFor more information, check out the blog post and the RSC Docs.
create-react-router - Add Deno as a supported and detectable package manager. Note that this detection will only work with Deno versions 2.0.5 and above. If you are using an older version version of Deno then you must specify the --package-manager CLI flag set to deno. (#12327)@react-router/remix-config-routes-adapter - Export DefineRouteFunction type alongside DefineRoutesFunction (#13945)react-router - Handle InvalidCharacterError when validating cookie signature (#13847)
react-router - Pass a copy of searchParams to the setSearchParams callback function to avoid mutations of the internal searchParams instance (#12784)
searchParams when a navigation is blocked because the internal instance gets out of sync with useLocation().searchreact-router - Support invalid Date in turbo-stream v2 fork (#13684)
react-router - In Framework Mode, clear critical CSS in development after initial render (#13872, #13995)
react-router - Strip search parameters from patchRoutesOnNavigation path param for fetcher calls (#13911)
react-router - Skip scroll restoration on useRevalidator() calls because they're not new locations (#13671)
react-router - Support unencoded UTF-8 routes in prerender config with ssr set to false (#13699)
react-router - Do not throw if the url hash is not a valid URI component (#13247)
react-router - Remove Content-Length header from Single Fetch responses (#13902)
react-router - Fix a regression in createRoutesStub introduced with the middleware feature (#13946)
As part of that work we altered the signature to align with the new middleware APIs without making it backwards compatible with the prior AppLoadContext API
This permitted createRoutesStub to work if you were opting into middleware and the updated context typings, but broke createRoutesStub for users not yet opting into middleware
We've reverted this change and re-implemented it in such a way that both sets of users can leverage it
⚠️ This may be a breaking bug for if you have adopted the unstable Middleware feature and are using createRoutesStub with the updated API.
// If you have not opted into middleware, the old API should work again
let context: AppLoadContext = {
/*...*/
};
let Stub = createRoutesStub(routes, context);
// If you have opted into middleware, you should now pass an instantiated
// `unstable_routerContextProvider` instead of a `getContext` factory function.
let context = new unstable_RouterContextProvider();
context.set(SomeContext, someValue);
let Stub = createRoutesStub(routes, context);
@react-router/dev - Update vite-node to ^3.2.2 to support Vite 7 (#13781)
@react-router/dev - Properly handle https protocol in dev mode (#13746)
@react-router/dev - Fix missing styles when Vite's build.cssCodeSplit option is disabled (#13943)
@react-router/dev - Allow .mts and .mjs extensions for route config file (#13931)
@react-router/dev - Fix prerender file locations when cwd differs from project root (#13824)
@react-router/dev - Improve chunk error logging when a chunk cannot be found during the build (#13799)
@react-router/dev - Fix incorrectly configured externalConditions which had enabled module condition for externals and broke builds with certain packages (like Emotion) (#13871)
⚠️ Unstable features are not recommended for production use
create-react-routerreact-router@react-router/architect@react-router/cloudflare@react-router/dev@react-router/express@react-router/fs-routes@react-router/node@react-router/remix-config-routes-adapter@react-router/serveFull Changelog: v7.6.3...v7.7.0
Date: 2025-06-27
react-router - Do not serialize types for useRouteLoaderData<typeof clientLoader> (#13752)
For types to distinguish a clientLoader from a serverLoader, you MUST annotate clientLoader args:
// 👇 annotation required to skip serializing types
export function clientLoader({}: Route.ClientLoaderArgs) {
return { fn: () => "earth" };
}
function SomeComponent() {
const data = useRouteLoaderData<typeof clientLoader>("routes/this-route");
const planet = data?.fn() ?? "world";
return <h1>Hello, {planet}!</h1>;
}
@react-router/cloudflare - Remove tsup from peerDependencies (#13757)
@react-router/dev - Add Vite 7 support (#13748)
@react-router/dev - Skip package.json resolution checks when a custom entry.server.(j|t)sx file is provided (#13744)
@react-router/dev - Add validation for a route's id not being 'root' (#13792)
@react-router/fs-routes @react-router/remix-config-routes-adapter - Use replaceAll for normalizing windows file system slashes (#13738)
@react-router/node - Remove old "install" package exports (#13762)
Full Changelog: v7.6.2...v7.6.3
Date: 2025-06-03
create-react-router - Update tar-fs (#13675)
react-router - (INTERNAL) Slight refactor of internal headers() function processing for use with RSC (#13639)
react-router @react-router/dev - Avoid additional with-props chunk in Framework Mode by moving route module component prop logic from the Vite plugin to react-router (#13650)
@react-router/dev - When future.unstable_viteEnvironmentApi is enabled and an absolute Vite base has been configured, ensure critical CSS is handled correctly during development (#13598)
@react-router/dev - Update vite-node (#13673)
@react-router/dev - Fix typegen for non-{.js,.jsx,.ts,.tsx} routes like .mdx (#12453)
@react-router/dev - Fix href types for optional dynamic params (#13725)
7.6.1 introduced fixes for href when using optional static segments,
but those fixes caused regressions with how optional dynamic params worked in 7.6.0:
// 7.6.0
href("/users/:id?"); // ✅
href("/users/:id?", { id: 1 }); // ✅
// 7.6.1
href("/users/:id?"); // ❌
href("/users/:id?", { id: 1 }); // ❌
Now, optional static segments are expanded into different paths for href, but optional dynamic params are not.
This way href can unambiguously refer to an exact URL path, all while keeping the number of path options to a minimum.
// 7.6.2
// path: /users/:id?/edit?
href("
// ^ suggestions when cursor is here:
//
// /users/:id?
// /users/:id?/edit
Additionally, you can pass params from component props without needing to narrow them manually:
declare const params: { id?: number };
// 7.6.0
href("/users/:id?", params);
// 7.6.1
href("/users/:id?", params); // ❌
"id" in params ? href("/users/:id", params) : href("/users"); // works... but is annoying
// 7.6.2
href("/users/:id?", params); // restores behavior of 7.6.0
Full Changelog: v7.6.1...v7.6.2
Date: 2025-05-25
react-router - Partially revert optimization added in 7.1.4 to reduce calls to matchRoutes because it surfaced other issues (#13562)
react-router - Update Route.MetaArgs to reflect that data can be potentially undefined (#13563)
loader threw an error to it's own ErrorBoundary, but it also arises in the case of a 404 which renders the root ErrorBoundary/meta but the root loader did not run because not routes matchedreact-router - Avoid initial fetcher execution 404 error when Lazy Route Discovery is interrupted by a navigation (#13564)
react-router - Properly href replaces splats * (#13593)
href("/products/*", { "*": "/1/edit" }); // -> /products/1/edit@react-router/architect - Update @architect/functions from ^5.2.0 to ^7.0.0 (#13556)
@react-router/dev - Prevent typegen with route files that are outside the app/ directory (#12996)
@react-router/dev - Add additional logging to build command output when cleaning assets from server build (#13547)
@react-router/dev - Don't clean assets from server build when build.ssrEmitAssets has been enabled in Vite config (#13547)
@react-router/dev - Fix typegen when same route is used at multiple paths (#13574)
For example, routes/route.tsx is used at 4 different paths here:
import { type RouteConfig, route } from "@react-router/dev/routes";
export default [
route("base/:base", "routes/base.tsx", [
route("home/:home", "routes/route.tsx", { id: "home" }),
route("changelog/:changelog", "routes/route.tsx", { id: "changelog" }),
route("splat/*", "routes/route.tsx", { id: "splat" }),
]),
route("other/:other", "routes/route.tsx", { id: "other" }),
] satisfies RouteConfig;
Previously, typegen would arbitrarily pick one of these paths to be the "winner" and generate types for the route module based on that path
Now, typegen creates unions as necessary for alternate paths for the same route file
@react-router/dev - Better types for params (#13543)
For example:
// routes.ts
import { type RouteConfig, route } from "@react-router/dev/routes";
export default [
route("parent/:p", "routes/parent.tsx", [
route("route/:r", "routes/route.tsx", [
route("child1/:c1a/:c1b", "routes/child1.tsx"),
route("child2/:c2a/:c2b", "routes/child2.tsx"),
]),
]),
] satisfies RouteConfig;
Previously, params for routes/route were calculated as { p: string, r: string }.
This incorrectly ignores params that could come from child routes
If visiting /parent/1/route/2/child1/3/4, the actual params passed to routes/route will have a type of { p: string, r: string, c1a: string, c1b: string }
Now, params are aware of child routes and autocompletion will include child params as optionals:
params.|
// ^ cursor is here and you ask for autocompletion
// p: string
// r: string
// c1a?: string
// c1b?: string
// c2a?: string
// c2b?: string
You can also narrow the types for params as it is implemented as a normalized union of params for each page that includes routes/route:
if (typeof params.c1a === 'string') {
params.|
// ^ cursor is here and you ask for autocompletion
// p: string
// r: string
// c1a: string
// c1b: string
}
@react-router/dev - Fix href for optional segments (#13595)
Type generation now expands paths with optionals into their corresponding non-optional paths
For example, the path /user/:id? gets expanded into /user and /user/:id to more closely model visitable URLs
href then uses these expanded (non-optional) paths to construct type-safe paths for your app:
// original: /user/:id?
// expanded: /user & /user/:id
href("/user"); // ✅
href("/user/:id", { id: 1 }); // ✅
This becomes even more important for static optional paths where there wasn't a good way to indicate whether the optional should be included in the resulting path:
// original: /products/:id/detail?
// before
href("/products/:id/detail?"); // ❌ How can we tell `href` to include or omit `detail?` segment with a complex API?
// now
// expanded: /products/:id & /products/:id/detail
href("/product/:id"); // ✅
href("/product/:id/detail"); // ✅
⚠️ Unstable features are not recommended for production use
@react-router/dev - Renamed internal react-router/route-module export to react-router/internal (#13543)@react-router/dev - Removed Info export from generated +types/* files (#13543)@react-router/dev - Normalize dirent entry path across node versions when generating SRI manifest (#13591)Full Changelog: v7.6.0...v7.6.1
Date: 2025-05-08
routeDiscovery Config OptionWe've added a new config option in 7.6.0 which grants you more control over the Lazy Route Discovery feature. You can now configure the /__manifest path if you're running multiple RR applications on the same server, or you can also disable the feature entirely if your application is small enough and the feature isn't necessary.
// react-router.config.ts
export default {
// You can modify the manifest path used:
routeDiscovery: { mode: "lazy", manifestPath: "/custom-manifest" }
// Or you can disable this feature entirely and include all routes in the
// manifest on initial document load:
routeDiscovery: { mode: "initial" }
// If you don't specify anything, the default config is as follows, which enables
// Lazy Route Discovery and makes manifest requests to the `/__manifest` path:
// routeDiscovery: { mode: "lazy", manifestPath: "/__manifest" }
} satisfies Config;
Some future flags alter the way types should work in React Router. Previously, you had to remember to manually opt-in to the new types. For example, for future.unstable_middleware:
// react-router.config.ts
// Step 1: Enable middleware
export default {
future: {
unstable_middleware: true,
},
};
// Step 2: Enable middleware types
declare module "react-router" {
interface Future {
unstable_middleware: true; // 👈 Enable middleware types
}
}
It was up to you to keep the runtime future flags synced with the types for those flags. This was confusing and error-prone.
Now, React Router will automatically enable types for future flags. That means you only need to specify the runtime future flag:
// react-router.config.ts
// Step 1: Enable middleware
export default {
future: {
unstable_middleware: true,
},
};
// No step 2! That's it!
Behind the scenes, React Router will generate the corresponding declare module into .react-router/types. Currently this is done in .react-router/types/+register.ts but this is an implementation detail that may change in the future.
react-router - Added a new routeDiscovery option in react-router.config.ts to configure Lazy Route Discovery behavior (#13451)
react-router - Add support for route component props in createRoutesStub (#13528)
This allows you to unit test your route components using the props instead of the hooks:
let RoutesStub = createRoutesStub([
{
path: "/",
Component({ loaderData }) {
let data = loaderData as { message: string };
return <pre data-testid="data">Message: {data.message}</pre>;
},
loader() {
return { message: "hello" };
},
},
]);
render(<RoutesStub />);
await waitFor(() => screen.findByText("Message: hello"));
@react-router/dev - Automatic types for future flags (#13506)
You may notice this list is a bit larger than usual! The team ate their vegetables last week and spent the week squashing bugs to work on lowering the issue count that had ballooned a bit since the v7 release.
react-router - Fix react-router module augmentation for NodeNext (#13498)react-router - Don't bundle react-router in react-router/dom CJS export (#13497)react-router - Fix bug where a submitting fetcher would get stuck in a loading state if a revalidating loader redirected (#12873)react-router - Fix hydration error if a server loader returned undefined (#13496)react-router - Fix initial load 404 scenarios in data mode (#13500)react-router - Stabilize useRevalidator's revalidate function (#13542)react-router - Preserve status code if a clientAction throws a data() result in framework mode (#13522)react-router - Be defensive against leading double slashes in paths to avoid Invalid URL errors from the URL constructor (#13510)
new URL("//", window.location.origin)react-router - Remove Navigator declaration for navigator.connection.saveData to avoid messing with any other types beyond saveData in user land (#13512)react-router - Fix handleError params values on .data requests for routes with a dynamic param as the last URL segment (#13481)react-router - Don't trigger an ErrorBoundary UI before the reload when we detect a manifest version mismatch in Lazy Route Discovery (#13480)react-router - Inline turbo-stream@2.4.1 dependency and fix decoding ordering of Map/Set instances (#13518)react-router - Only render dev warnings during dev (#13461)react-router - Short circuit post-processing on aborted dataStrategy requests (#13521)
Cannot read properties of undefined (reading 'result')@react-router/dev - Support project root directories without a package.json if it exists in a parent directory (#13472)@react-router/dev - When providing a custom Vite config path via the CLI --config/-c flag, default the project root directory to the directory containing the Vite config when not explicitly provided (#13472)@react-router/dev - In a routes.ts context, ensure the --mode flag is respected for import.meta.env.MODE (#13485)
import.meta.env.MODE within a routes.ts context was always "development" for the dev and typegen --watch commands, but otherwise resolved to "production". These defaults are still in place, but if a --mode flag is provided, this will now take precedence.@react-router/dev - Ensure consistent project root directory resolution logic in CLI commands (#13472)@react-router/dev - When executing react-router.config.ts and routes.ts with vite-node, ensure that PostCSS config files are ignored (#13489)@react-router/dev - When extracting critical CSS during development, ensure it's loaded from the client environment to avoid issues with plugins that handle the SSR environment differently (#13503)@react-router/dev - Fix "Status message is not supported by HTTP/2" error during dev when using HTTPS (#13460)@react-router/dev - Update config when react-router.config.ts is created or deleted during development (#12319)@react-router/dev - Skip unnecessary routes.ts evaluation before Vite build is started (#13513)@react-router/dev - Fix TS2300: Duplicate identifier errors caused by generated types (#13499)href (.react-router/types/+register.ts), causing type checking errors⚠️ Unstable features are not recommended for production use
react-router - Fix a few bugs with error bubbling in middleware use-cases (#13538)@react-router/dev - When future.unstable_viteEnvironmentApi is enabled, ensure that build.assetsDir in Vite config is respected when environments.client.build.assetsDir is not configured (#13491)create-react-routerreact-router@react-router/architect@react-router/cloudflare@react-router/dev@react-router/express@react-router/fs-routes@react-router/node@react-router/remix-config-routes-adapter@react-router/serveFull Changelog: v7.5.3...v7.6.0
Date: 2025-04-28
react-router - Fix bug where bubbled action errors would result in loaderData being cleared at the handling ErrorBoundary route (#13476)react-router - Handle redirects from clientLoader.hydrate initial load executions (#13477)Full Changelog: v7.5.2...v7.5.3
Date: 2025-04-24
Fixed 2 security vulnerabilities that could result in cache-poisoning attacks by sending specific headers intended for build-time usage for SPA Mode and Pre-rendering (GHSA-f46r-rw29-r322, GHSA-cpj6-fhp6-mr6j).
react-router - Adjust approach for Pre-rendering/SPA Mode via headers (#13453)react-router - Update Single Fetch to also handle the 204 redirects used in ?_data requests in Remix v2 (#13364)
.data requests from outside the scope of React Router (i.e., an express/hono middleware) the same way they did in Remix v2 before Single Fetch was implemented.data request wih a response as follows:
X-Remix-Redirect: <new-location> headerX-Remix-Replace: true or X-Remix-Reload-Document: true headers to replicate replace()/redirectDocument() functionalityFull Changelog: v7.5.1...v7.5.2
Date: 2025-04-17
react-router - When using the object-based route.lazy API, the HydrateFallback and hydrateFallbackElement properties are now skipped when lazy loading routes after hydration (#13376)
If you move the code for these properties into a separate file, since the hydrate properties were unused already (if the route wasn't present during hydration), you can avoid downloading them at all. For example:
createBrowserRouter([
{
path: "/show/:showId",
lazy: {
loader: async () => (await import("./show.loader.js")).loader,
Component: async () =>
(await import("./show.component.js")).Component,
HydrateFallback: async () =>
(await import("./show.hydrate-fallback.js")).HydrateFallback,
},
},
]);
react-router - Fix single fetch bug where no revalidation request would be made when navigating upwards to a reused parent route (#13253)
react-router - Properly revalidate pre-rendered paths when param values change when using ssr:false + prerender configs (#13380)
react-router - Fix pre-rendering when a loader returns a redirect (#13365)
react-router - Do not automatically add null to staticHandler.query() context.loaderData if routes do not have loaders (#13223)
undefined from loaders, our prior check of loaderData[routeId] !== undefined was no longer sufficient and was changed to a routeId in loaderData check - these null values can cause issues for this new checkcreateStaticHandler()/<StaticRouterProvider>, and using context.loaderData to control <RouterProvider> hydration behavior on the client⚠️ Unstable features are not recommended for production use
react-router - Add better error messaging when getLoadContext is not updated to return a Map (#13242)react-router - Update context type for LoaderFunctionArgs/ActionFunctionArgs when middleware is enabled (#13381)react-router - Add a new unstable_runClientMiddleware argument to dataStrategy to enable middleware execution in custom dataStrategy implementations (#13395)react-router - Add support for the new unstable_shouldCallHandler/unstable_shouldRevalidateArgs APIs in dataStrategy (#13253)Full Changelog: v7.5.0...v7.5.1
Date: 2025-04-04
route.lazy Object APIWe've introduced a new route.lazy API which gives you more granular control over the lazy loading of route properties that you could not achieve with the route.lazy() function signature. This is useful for Framework mode and performance-critical library mode applications.
createBrowserRouter([
{
path: "/show/:showId",
lazy: {
loader: async () => (await import("./show.loader.js")).loader,
action: async () => (await import("./show.action.js")).action,
Component: async () => (await import("./show.component.js")).Component,
},
},
]);
⚠️ This is a breaking change if you have adopted the route.unstable_lazyMiddleware API which has been removed in favor of route.lazy.unstable_middleware. See the Unstable Changes section below for more information.
react-router - Add granular object-based API for route.lazy to support lazy loading of individual route properties (#13294)@react-router/dev - Update optional wrangler peer dependency range to support wrangler v4 (#13258)@react-router/dev - Reinstate dependency optimization in the child compiler to fix depsOptimizer is required in dev mode errors when using vite-plugin-cloudflare and importing Node.js builtins (#13317)⚠️ Unstable features are not recommended for production use
react-router - Introduce future.unstable_subResourceIntegrity flag that enables generation of an importmap with integrity for the scripts that will be loaded by the browser (#13163)react-router - Remove support for the route.unstable_lazyMiddleware property (#13294)
route.lazy.unstable_middleware API@react-router/dev - When future.unstable_viteEnvironmentApi is enabled, ensure critical CSS in development works when using a custom Vite base has been configured (#13305)create-react-routerreact-router@react-router/architect@react-router/cloudflare@react-router/dev@react-router/express@react-router/fs-routes@react-router/node@react-router/remix-config-routes-adapter@react-router/serveFull Changelog: v7.4.1...v7.5.0
Date: 2025-03-28
Fixed a security vulnerability that allowed URL manipulation and potential cache pollution via the Host and X-Forwarded-Host headers due to inadequate port sanitization (GHSA-4q56-crqp-v477/CVE-2025-31137).
react-router - Dedupe calls to route.lazy functions (#13260)@react-router/dev - Fix path in prerender error messages (#13257)@react-router/dev - Fix typegen for virtual modules when moduleDetection is set to force (#13267)@react-router/express - Better validation of x-forwarded-host header to prevent potential security issues (#13309)⚠️ Unstable features are not recommended for production use
react-router - Fix types on unstable_MiddlewareFunction to avoid type errors when a middleware doesn't return a value (#13311)react-router - Add support for route.unstable_lazyMiddleware function to allow lazy loading of middleware logic (#13210)
unstable_middleware from route.lazyroute.unstable_middleware property is no longer supported in the return value from route.lazyroute.unstable_lazyMiddleware@react-router/dev - When both future.unstable_middleware and future.unstable_splitRouteModules are enabled, split unstable_clientMiddleware route exports into separate chunks when possible (#13210)@react-router/dev - Improve performance of future.unstable_middleware by ensuring that route modules are only blocking during the middleware phase when the unstable_clientMiddleware has been defined (#13210)Full Changelog: v7.4.0...v7.4.1
Date: 2025-03-19
@react-router/dev - Generate types for virtual:react-router/server-build module (#13152)react-router - Fix root loader data on initial load redirects in SPA mode (#13222)react-router - Load ancestor pathless/index routes in lazy route discovery for upwards non-eager-discovery routing (#13203)react-router - Fix shouldRevalidate behavior for clientLoader-only routes in ssr:true apps (#13221)@react-router/dev - Fix conflicts with other Vite plugins that use the configureServer and/or configurePreviewServer hooks (#13184)⚠️ Unstable features are not recommended for production use
react-router - If a middleware throws an error, ensure we only bubble the error itself via next() and are no longer leaking the MiddlewareError implementation detail (#13180)
catch-ing errors thrown by the next() function in your middlewaresreact-router - Fix RequestHandler loadContext parameter type when middleware is enabled (#13204)react-router - Update Route.unstable_MiddlewareFunction to have a return value of Response | undefined instead of Response | void (#13199)@react-router/dev - When future.unstable_splitRouteModules is set to "enforce", allow both splittable and unsplittable root route exports since it's always in a single chunk (#13238)@react-router/dev - When future.unstable_viteEnvironmentApi is enabled, allow plugins that override the default SSR environment (such as @cloudflare/vite-plugin) to be placed before or after the React Router plugin (#13183)create-react-routerreact-router@react-router/architect@react-router/cloudflare@react-router/dev@react-router/express@react-router/fs-routes@react-router/node@react-router/remix-config-routes-adapter@react-router/serveFull Changelog: v7.3.0...v7.4.0
Date: 2025-03-06
fetcherKey as a parameter to patchRoutesOnNavigation (#13061)react-router - Detect and handle manifest-skew issues on new deploys during active sessions (#13061)
fetcher calls to undiscovered routes, this mismatch will trigger a document reload of the current pathreact-router - Skip resource route flow in dev server in SPA mode (#13113)react-router - Fix single fetch _root.data requests when a basename is used (#12898)react-router - Fix types for loaderData and actionData that contained Records (#13139)
unstable_SerializesTo - see the note in the Unstable Changes section below for more information@react-router/dev - Fix support for custom client build.rollupOptions.output.entryFileNames (#13098)@react-router/dev - Fix usage of prerender option when serverBundles option has been configured or provided by a preset, e.g. vercelPreset from @vercel/react-router (#13082)@react-router/dev - Fix support for custom build.assetsDir (#13077)@react-router/dev - Remove unused dependencies (#13134)@react-router/dev - Stub all routes except root in "SPA Mode" server builds to avoid issues when route modules or their dependencies import non-SSR-friendly modules (#13023)@react-router/dev - Remove unused Vite file system watcher (#13133)@react-router/dev - Fix support for custom SSR build input when serverBundles option has been configured (#13107)
future.unstable_viteEnvironmentApi and serverBundles options together, hyphens are no longer supported in server bundle IDs since they also need to be valid Vite environment names.@react-router/dev - Fix dev server when using HTTPS by stripping HTTP/2 pseudo headers from dev server requests (#12830)@react-router/dev - Lazy load Cloudflare platform proxy on first dev server request when using the cloudflareDevProxy Vite plugin to avoid creating unnecessary workerd processes (#13016)@react-router/dev - Fix duplicated entries in typegen for layout routes and their corresponding index route (#13140)@react-router/express - Update express peerDependency to include v5 (https://github.com/remix-run/react-router/pull/13064) (#12961)⚠️ Unstable features are not recommended for production use
react-router - Add context support to client side data routers (unstable) (#12941)react-router - Support middleware on routes (unstable) (#12941)@react-router/dev - Fix errors with future.unstable_viteEnvironmentApi when the ssr environment has been configured by another plugin to be a custom Vite.DevEnvironment rather than the default Vite.RunnableDevEnvironment (#13008)@react-router/dev - When future.unstable_viteEnvironmentApi is enabled and the ssr environment has optimizeDeps.noDiscovery disabled, define optimizeDeps.entries and optimizeDeps.include (#13007)context (unstable)Your application clientLoader/clientAction functions (or loader/action in library mode) will now receive a context parameter on the client. This is an instance of unstable_RouterContextProvider that you use with type-safe contexts (similar to React.createContext) and is most useful with the corresponding unstable_clientMiddleware API:
import { unstable_createContext } from "react-router";
type User = {
/*...*/
};
const userContext = unstable_createContext<User>();
const sessionMiddleware: Route.unstable_ClientMiddlewareFunction = async ({
context,
}) => {
let user = await getUser();
context.set(userContext, user);
};
export const unstable_clientMiddleware = [sessionMiddleware];
export function clientLoader({ context }: Route.ClientLoaderArgs) {
let user = context.get(userContext);
let profile = await getProfile(user.id);
return { profile };
}
Similar to server-side requests, a fresh context will be created per navigation (or fetcher call). If you have initial data you'd like to populate in the context for every request, you can provide an unstable_getContext function at the root of your app:
createBrowserRouter(routes, { unstable_getContext })<HydratedRouter unstable_getContext>This function should return an value of type unstable_InitialContext which is a Map<unstable_RouterContext, unknown> of context's and initial values:
const loggerContext = unstable_createContext<(...args: unknown[]) => void>();
function logger(...args: unknown[]) {
console.log(new Date.toISOString(), ...args);
}
function unstable_getContext() {
let map = new Map();
map.set(loggerContext, logger);
return map;
}
Middleware is implemented behind a future.unstable_middleware flag. To enable, you must enable the flag and the types in your react-router.config.ts file:
import type { Config } from "@react-router/dev/config";
import type { Future } from "react-router";
declare module "react-router" {
interface Future {
unstable_middleware: true; // 👈 Enable middleware types
}
}
export default {
future: {
unstable_middleware: true, // 👈 Enable middleware
},
} satisfies Config;
⚠️ Middleware is unstable and should not be adopted in production. There is at least one known de-optimization in route module loading for clientMiddleware that we will be addressing this before a stable release.
⚠️ Enabling middleware contains a breaking change to the context parameter passed to your loader/action functions - see below for more information.
Once enabled, routes can define an array of middleware functions that will run sequentially before route handlers run. These functions accept the same parameters as loader/action plus an additional next parameter to run the remaining data pipeline. This allows middlewares to perform logic before and after handlers execute.
// Framework mode
export const unstable_middleware = [serverLogger, serverAuth]; // server
export const unstable_clientMiddleware = [clientLogger]; // client
// Library mode
const routes = [
{
path: "/",
// Middlewares are client-side for library mode SPA's
unstable_middleware: [clientLogger, clientAuth],
loader: rootLoader,
Component: Root,
},
];
Here's a simple example of a client-side logging middleware that can be placed on the root route:
const clientLogger: Route.unstable_ClientMiddlewareFunction = async (
{ request },
next,
) => {
let start = performance.now();
// Run the remaining middlewares and all route loaders
await next();
let duration = performance.now() - start;
console.log(`Navigated to ${request.url} (${duration}ms)`);
};
Note that in the above example, the next/middleware functions don't return anything. This is by design as on the client there is no "response" to send over the network like there would be for middlewares running on the server. The data is all handled behind the scenes by the stateful router.
For a server-side middleware, the next function will return the HTTP Response that React Router will be sending across the wire, thus giving you a chance to make changes as needed. You may throw a new response to short circuit and respond immediately, or you may return a new or altered response to override the default returned by next().
const serverLogger: Route.unstable_MiddlewareFunction = async (
{ request, params, context },
next,
) => {
let start = performance.now();
// 👇 Grab the response here
let res = await next();
let duration = performance.now() - start;
console.log(`Navigated to ${request.url} (${duration}ms)`);
// 👇 And return it here (optional if you don't modify the response)
return res;
};
You can throw a redirect from a middleware to short circuit any remaining processing:
import { sessionContext } from "../context";
const serverAuth: Route.unstable_MiddlewareFunction = (
{ request, params, context },
next,
) => {
let session = context.get(sessionContext);
let user = session.get("user");
if (!user) {
session.set("returnTo", request.url);
throw redirect("/login", 302);
}
};
Note that in cases like this where you don't need to do any post-processing you don't need to call the next function or return a Response.
Here's another example of using a server middleware to detect 404s and check the CMS for a redirect:
const redirects: Route.unstable_MiddlewareFunction = async ({
request,
next,
}) => {
// attempt to handle the request
let res = await next();
// if it's a 404, check the CMS for a redirect, do it last
// because it's expensive
if (res.status === 404) {
let cmsRedirect = await checkCMSRedirects(request.url);
if (cmsRedirect) {
throw redirect(cmsRedirect, 302);
}
}
return res;
};
For more information on the middleware API/design, please see the decision doc.
context parameterWhen middleware is enabled, your application will use a different type of context parameter in your loaders and actions to provide better type safety. Instead of AppLoadContext, context will now be an instance of ContextProvider that you can use with type-safe contexts (similar to React.createContext):
import { unstable_createContext } from "react-router";
import { Route } from "./+types/root";
import type { Session } from "./sessions.server";
import { getSession } from "./sessions.server";
let sessionContext = unstable_createContext<Session>();
const sessionMiddleware: Route.unstable_MiddlewareFunction = ({
context,
request,
}) => {
let session = await getSession(request);
context.set(sessionContext, session);
// ^ must be of type Session
};
// ... then in some downstream middleware
const loggerMiddleware: Route.unstable_MiddlewareFunction = ({
context,
request,
}) => {
let session = context.get(sessionContext);
// ^ typeof Session
console.log(session.get("userId"), request.method, request.url);
};
// ... or some downstream loader
export function loader({ context }: Route.LoaderArgs) {
let session = context.get(sessionContext);
let profile = await getProfile(session.get("userId"));
return { profile };
}
If you are using a custom server with a getLoadContext function, the return value for initial context values passed from the server adapter layer is no longer an object and should now return an unstable_InitialContext (Map<RouterContext, unknown>):
let adapterContext = unstable_createContext<MyAdapterContext>();
function getLoadContext(req, res): unstable_InitialContext {
let map = new Map();
map.set(adapterContext, getAdapterContext(req));
return map;
}
unstable_SerializesTounstable_SerializesTo added a way to register custom serialization types in Single Fetch for other library and framework authors like Apollo. It was implemented with branded type whose branded property that was made optional so that casting arbitrary values was easy:
// without the brand being marked as optional
let x1 = 42 as unknown as unstable_SerializesTo<number>;
// ^^^^^^^^^^
// with the brand being marked as optional
let x2 = 42 as unstable_SerializesTo<number>;
However, this broke type inference in loaderData and actionData for any Record types as those would now (incorrectly) match unstable_SerializesTo. This affected all users, not just those that depended on unstable_SerializesTo. To fix this, the branded property of unstable_SerializesTo is marked as required instead of optional.
For library and framework authors using unstable_SerializesTo, you may need to add as unknown casts before casting to unstable_SerializesTo.
create-react-routerreact-router@react-router/architect@react-router/cloudflare@react-router/dev@react-router/express@react-router/fs-routes@react-router/node@react-router/remix-config-routes-adapter@react-router/serveFull Changelog: v7.2.0...v7.3.0
Date: 2025-02-18
href utilityIn framework mode, we now provide you with a fully type-safe href utility to give you all the warm and fuzzy feelings of path auto-completion and param validation for links in your application:
import { href } from "react-router";
export default function Component() {
const link = href("/blog/:slug", { slug: "my-first-post" });
// ^ type-safe! ^ Also type-safe!
return (
<main>
<Link to={href("/products/:id", { id: "asdf" })} />
<NavLink to={href("/:lang?/about", { lang: "en" })} />
</main>
);
}
You'll now get type errors if you pass a bad path value or a bad param value:
const badPath = href("/not/a/valid/path");
// ^ Error!
const badParam = href("/blog/:slug", { oops: "bad param" });
// ^ Error!
This release enhances the ability to use a combination of pre-rendered paths alongside other paths that operate in "SPA Mode" when pre-rendering with ssr:false.
ssr:false without a prerender config, this is considered "SPA Mode" and the generated index.html file will only render down to the root route and will be able to hydrate for any valid application pathssr:false with a prerender config but do not include the / path (i.e., prerender: ['/blog/post']), then we still generate a "SPA Mode" index.html file that can hydrate for any path in the applicationssr:false and include the / path in your prerender config, the generated index.html file will be specific to the root index route, so we will now also generate a separate "SPA Mode" file in __spa-fallback.html that you can serve/hydrate for non-prerendered pathsFor more info, see the Pre-rendering docs for more info.
loader in SPA ModeSPA Mode used to prohibit the use of loaders in all routes so that we could hydrate for any path in the application. However, because the root route is always rendered at build time, we can lift this restriction for the root route.
In order to use your build-time loader data during pre-rendering, we now also expose the loaderData as an optional prop for the HydrateFallback component on routes:
HydrateFallback is rendering because children routes are loadingundefined if the HydrateFallback is rendering because the route itself has it's own hydrating clientLoader
react-router - New type-safe href utility that guarantees links point to actual paths in your app (#13012)@react-router/dev - Generate a "SPA fallback" HTML file when pre-rendering the / route with ssr:false (#12948)@react-router/dev - Allow a loader in the root route in SPA mode because it can be called/server-rendered at build time (#12948)
Route.HydrateFallbackProps now also receives loaderDatareact-router - Disable Lazy Route Discovery for all ssr:false apps and not just "SPA Mode" because there is no runtime server to serve the search-param-configured __manifest requests (#12894)
ssr:false appsprerender scenarios we would pre-render the /__manifest file but that makes some unnecessary assumptions about the static file server behaviorsreact-router - Don't apply Single Fetch revalidation de-optimization when in SPA mode since there is no server HTTP request (#12948)react-router - Properly handle revalidations to across a pre-render/SPA boundary (#13021)
.data requests if the path wasn't pre-rendered because the request will 404loader data in ssr:false mode is static because it's generated at build timeclientLoader to do anything dynamicloader and not a clientLoader, we disable revalidation by default because there is no new data to retrieve.data request logic if there are no server loaders with shouldLoad=true in our single fetch dataStrategy.data request that would 404 after a submissionreact-router - Align dev server behavior with static file server behavior when ssr:false is set (#12948)
prerender config exists, only SSR down to the root HydrateFallback (SPA Mode)prerender config exists but the current path is not pre-rendered, only SSR down to the root HydrateFallback (SPA Fallback).data requests to non-pre-rendered pathsreact-router - Improve prefetch performance of CSS side effects in framework mode (#12889)react-router - Properly handle interrupted manifest requests in lazy route discovery (#12915)@react-router/dev - Handle custom envDir in Vite config (#12969)@react-router/dev - Fix CLI parsing to allow argument-less npx react-router usage (#12925)@react-router/dev - Skip action-only resource routes when using prerender:true (#13004)@react-router/dev - Enhance invalid export detection when using ssr:false (#12948)
headers/action functions are prohibited in all routes with ssr:false because there will be no runtime server on which to run themloader functions are more nuanced and depend on whether a given route is prerendered
ssr:false without a prerender config, only the root route can have a loaderssr:false with a prerender config, only routes matched by a prerender path can have a loader@react-router/dev - Error at build time in ssr:false + prerender apps for the edge case scenario of: (#13021)
loader (does not have a clientLoader)loaderData because there is no server on which to run the loaderclientLoader or pre-rendering the child pathsclientLoader, calling the serverLoader() on non-prerendered paths will throw a 404@react-router/dev - Limit prerendered resource route .data files to only the target route (#13004)@react-router/dev - Fix pre-rendering of binary files (#13039)@react-router/dev - Fix typegen for repeated params (#13012)
/a/:id/b/:id?/c/:id, the last :id will set the value for id in useParams and the params prop
/a/1/b/2/c/3 will result in the value { id: 3 } at runtime/a/1/b/2/c/3 generated a type like { id: [1,2,3] }./a/1/b/2/c/3 now generates a type like { id: 3 }.@react-router/dev - Fix path to load package.json for react-router --version (#13012)⚠️ Unstable features are not recommended for production use
react-router - Add unstable_SerializesTo brand type for library authors to register types serializable by React Router's streaming format (turbo-stream) (#12264)@react-router/dev - Add unstable support for splitting route modules in framework mode via future.unstable_splitRouteModules (#11871)@react-router/dev - Add future.unstable_viteEnvironmentApi flag to enable experimental Vite Environment API support (#12936)⚠️ This feature is currently unstable, enabled by the
future.unstable_splitRouteModulesflag. We’d love any interested users to play with it locally and provide feedback, but we do not recommend using it in production yet.If you do choose to adopt this flag in production, please ensure you do sufficient testing against your production build to ensure that the optimization is working as expected.
One of the conveniences of the Route Module API is that everything a route needs is in a single file. Unfortunately this comes with a performance cost in some cases when using the clientLoader, clientAction, and HydrateFallback APIs.
As a basic example, consider this route module:
import { MassiveComponent } from "~/components";
export async function clientLoader() {
return await fetch("https://example.com/api").then((response) =>
response.json(),
);
}
export default function Component({ loaderData }) {
return <MassiveComponent data={loaderData} />;
}
In this example we have a minimal clientLoader export that makes a basic fetch call, whereas the default component export is much larger. This is a problem for performance because it means that if we want to navigate to this route client-side, the entire route module must be downloaded before the client loader can start running.
To visualize this as a timeline:
Get Route Module: |--=======|
Run clientLoader: |-----|
Render: |-|
Instead, we want to optimize this to the following:
Get clientLoader: |--|
Get Component: |=======|
Run clientLoader: |-----|
Render: |-|
To achieve this optimization, React Router will split the route module into multiple smaller modules during the production build process. In this case, we'll end up with two separate virtual modules — one for the client loader and one for the component and its dependencies.
export async function clientLoader() {
return await fetch("https://example.com/api").then((response) =>
response.json(),
);
}
import { MassiveComponent } from "~/components";
export default function Component({ loaderData }) {
return <MassiveComponent data={loaderData} />;
}
💡 This optimization is automatically applied in framework mode, but you can also implement it in library mode via
route.lazyand authoring your route in multiple files as covered in our blog post on lazy loading route modules.
Now that these are available as separate modules, the client loader and the component can be downloaded in parallel. This means that the client loader can be executed as soon as it's ready without having to wait for the component.
This optimization is even more pronounced when more Route Module APIs are used. For example, when using clientLoader, clientAction and HydrateFallback, the timeline for a single route module during a client-side navigation might look like this:
Get Route Module: |--~~++++=======|
Run clientLoader: |-----|
Render: |-|
This would instead be optimized to the following:
Get clientLoader: |--|
Get clientAction: |~~|
Get HydrateFallback: SKIPPED
Get Component: |=======|
Run clientLoader: |-----|
Render: |-|
Note that this optimization only works when the Route Module APIs being split don't share code within the same file. For example, the following route module can't be split:
import { MassiveComponent } from "~/components";
const shared = () => console.log("hello");
export async function clientLoader() {
shared();
return await fetch("https://example.com/api").then((response) =>
response.json(),
);
}
export default function Component({ loaderData }) {
shared();
return <MassiveComponent data={loaderData} />;
}
This route will still work, but since both the client loader and the component depend on the shared function defined within the same file, it will be de-optimized into a single route module.
To avoid this, you can extract any code shared between exports into a separate file. For example:
export const shared = () => console.log("hello");
You can then import this shared code in your route module without triggering the de-optimization:
import { MassiveComponent } from "~/components";
import { shared } from "./shared";
export async function clientLoader() {
shared();
return await fetch("https://example.com/api").then((response) =>
response.json(),
);
}
export default function Component({ loaderData }) {
shared();
return <MassiveComponent data={loaderData} />;
}
Since the shared code is in its own module, React Router is now able to split this route module into two separate virtual modules:
import { shared } from "./shared";
export async function clientLoader() {
shared();
return await fetch("https://example.com/api").then((response) =>
response.json(),
);
}
import { MassiveComponent } from "~/components";
import { shared } from "./shared";
export default function Component({ loaderData }) {
shared();
return <MassiveComponent data={loaderData} />;
}
If your project is particularly performance sensitive, you can set the unstable_splitRouteModules future flag to "enforce":
export default {
future: {
unstable_splitRouteModules: "enforce",
},
};
This setting will raise an error if any route modules can't be split:
Error splitting route module: routes/example/route.tsx
- clientLoader
This export could not be split into its own chunk because it shares code with other exports. You should extract any shared code into its own module and then import it within the route module.
create-react-routerreact-router@react-router/architect@react-router/cloudflare@react-router/dev@react-router/express@react-router/fs-routes@react-router/node@react-router/remix-config-routes-adapter@react-router/serveFull Changelog: v7.1.5...v7.2.0
Date: 2025-01-31
react-router - Fix regression introduced in 7.1.4 via #12800 that caused issues navigating to hash routes inside splat routes for applications using Lazy Route Discovery (patchRoutesOnNavigation) (#12927)Full Changelog: v7.1.4...v7.1.5
Date: 2025-01-30
@react-router/dev - Properly resolve Windows file paths to scan for Vite's dependency optimization when using the unstable_optimizeDeps future flag (#12637)@react-router/dev - Fix prerendering when using a custom server - previously we ended up trying to import the users custom server when we actually want to import the virtual server build module (#12759)react-router - Properly handle status codes that cannot have a body in single fetch responses (204, etc.) (#12760)react-router - Properly bubble headers as errorHeaders when throwing a data() result (#12846)
Set-Cookie headers if also returned from headersreact-router - Stop erroring on resource routes that return raw strings/objects and instead serialize them as text/plain or application/json responses (#12848)
.data extension.data request, they will still be encoded via turbo-streamreact-router - Optimize Lazy Route Discovery path discovery to favor a single querySelectorAll call at the body level instead of many calls at the sub-tree level (#12731)react-router - Optimize route matching by skipping redundant matchRoutes calls when possible (#12800, #12882)react-router - Internal reorg to clean up some duplicated route module types (#12799)Full Changelog: v7.1.3...v7.1.4
Date: 2025-01-17
@react-router/dev - Fix reveal and routes CLI commands (#12745)Full Changelog: v7.1.2...v7.1.3
Date: 2025-01-16
react-router - Fix issue with fetcher data cleanup in the data layer on fetcher unmount (#12681)react-router - Do not rely on symbol for filtering out redirect responses from loader data (#12694)
error TS4058: Return type of exported function has or is using name 'redirectSymbol' from external module "node_modules/..." but cannot be named.
symbols are not used for the redirect response type, these errors should no longer be present@react-router/dev - Fix default external conditions in Vite v6 (#12644)
@react-router/dev - Fix mismatch in prerendering html/data files when path is missing a leading slash (#12684)@react-router/dev - Use module-sync server condition when enabled in the runtime. This fixes React context mismatches (e.g. useHref() may be used only in the context of a <Router> component.) during development on Node 22.10.0+ when using libraries that have a peer dependency on React Router (#12729)@react-router/dev - Fix react-refresh source maps (#12686)Full Changelog: v7.1.1...v7.1.2
Date: 2024-12-23
@react-router/dev - Fix for a crash when optional args are passed to the CLI (#12609)Full Changelog: v7.1.0...v7.1.1
Date: 2024-12-20
react-router - Throw unwrapped Single Fetch redirect to align with pre-Single Fetch behavior (#12506)react-router - Ignore redirects when inferring loader data types (#12527)react-router - Remove <Link prefetch> warning which suffers from false positives in a lazy route discovery world (#12485)create-react-router - Fix missing fs-extra dependency (#12556)@react-router/dev/@react-router/serve - Properly initialize NODE_ENV if not already set for compatibility with React 19 (#12578)@react-router/dev - Remove the leftover/unused abortDelay prop from ServerRouter and update the default entry.server.tsx to use the new streamTimeout value for Single Fetch (#12478)
abortDelay functionality was removed in v7 as it was coupled to the defer implementation from Remix v2, but this removal of this prop was missedentry.server file, it's likely your app is not aborting streams as you would expect and you will need to adopt the new streamTimeout value introduced with Single Fetch@react-router/fs-routes - Throw error in flatRoutes if routes directory is missing (#12407)create-react-routerreact-router@react-router/architect@react-router/cloudflare@react-router/dev@react-router/express@react-router/fs-routes@react-router/node@react-router/remix-config-routes-adapter@react-router/serveFull Changelog: v7.0.2...v7.1.0
Date: 2024-12-02
react-router - Temporarily only use one build in export map so packages can have a peer dependency on react router (#12437)@react-router/dev - Support moduleResolution Node16 and NodeNext (#12440)@react-router/dev - Generate wide matches and params types for child routes (#12397)
matches includes child route matches and params include child route path parametersmatches and paramsFull Changelog: v7.0.1...v7.0.2
Date: 2024-11-22
@react-router/dev - Ensure typegen file watcher is cleaned up when Vite dev server restarts (#12331)@react-router/dev - Pass route error to ErrorBoundary as a prop (#12338)Full Changelog: v7.0.0...v7.0.1
Date: 2024-11-21
react-router-dom, @remix-run/react, @remix-run/server-runtime, and @remix-run/router have been collapsed into the react-router package
react-router-dom is still published in v7 as a re-export of everything from react-router@remix-run/cloudflare-pages and @remix-run/cloudflare-workers have been collapsed into @react-router/cloudflare package`react-router-dom-v5-compat and react-router-native packages are removed starting with v7Remix v2 used to re-export all common @remix-run/server-runtime APIs through the various runtime packages (node, cloudflare, deno) so that you wouldn't need an additional @remix-run/server-runtime dependency in your package.json. With the collapsing of packages into react-router, these common APIs are now no longer re-exported through the runtime adapters. You should import all common APIs from react-router, and only import runtime-specific APIs from the runtime packages:
// Runtime-specific APIs
import { createFileSessionStorage } from "@react-router/node";
// Runtime-agnostic APIs
import { redirect, useLoaderData } from "react-router";
The following APIs have been removed in React Router v7:
jsondeferunstable_composeUploadHandlersunstable_createMemoryUploadHandlerunstable_parseMultipartFormDataReact Router v7 requires the following minimum versions:
node@20
installGlobals method to polyfill the fetch APIreact@18, react-dom@18Remix and React Router follow an API Development Strategy leveraging "Future Flags" to avoid introducing a slew of breaking changes in a major release. Instead, breaking changes are introduced in minor releases behind a flag, allowing users to opt-in at their convenience. In the next major release, all future flag behaviors become the default behavior.
The following previously flagged behaviors are now the default in React Router v7:
future.v7_relativeSplatPathfuture.v7_startTransitionfuture.v7_fetcherPersistfuture.v7_normalizeFormMethodfuture.v7_partialHydrationfuture.v7_skipActionStatusRevalidationfuture.v3_fetcherPersistfuture.v3_relativeSplatPathfuture.v3_throwAbortReasonfuture.v3_singleFetchfuture.v3_lazyRouteDiscoveryfuture.v3_optimizeDepsThe Remix Vite plugin is the proper way to build full-stack SSR apps using React Router v7. The former esbuild-based compiler is no longer available.
Renamed vitePlugin and cloudflareDevProxyVitePlugin
For Remix consumers migrating to React Router, the vitePlugin and cloudflareDevProxyVitePlugin exports have been renamed and moved (#11904)
-import {
- vitePlugin as remix,
- cloudflareDevProxyVitePlugin,
-} from "@remix/dev";
+import { reactRouter } from "@react-router/dev/vite";
+import { cloudflareDevProxy } from "@react-router/dev/vite/cloudflare";
Removed manifest option
For Remix consumers migrating to React Router, the Vite plugin's manifest option has been removed. The manifest option been superseded by the more powerful buildEnd hook since it's passed the buildManifest argument. You can still write the build manifest to disk if needed, but you'll most likely find it more convenient to write any logic depending on the build manifest within the buildEnd hook itself. (#11573)
If you were using the manifest option, you can replace it with a buildEnd hook that writes the manifest to disk like this:
// react-router.config.ts
import { type Config } from "@react-router/dev/config";
import { writeFile } from "node:fs/promises";
export default {
async buildEnd({ buildManifest }) {
await writeFile(
"build/manifest.json",
JSON.stringify(buildManifest, null, 2),
"utf-8"
);
},
} satisfies Config;
Because React 19 will have first-class support for handling promises in the render pass (via React.use and useAction), we are now comfortable exposing the promises for the APIs that previously returned undefined:
useNavigate()useSubmit()useFetcher().loaduseFetcher().submituseRevalidator().revalidate()routes.tsWhen using the React Router Vite plugin, routes are defined in app/routes.ts. Route config is exported via the routes export, conforming to the RouteConfig type. Route helper functions route, index, and layout are provided to make declarative type-safe route definitions easier.
// app/routes.ts
import {
type RouteConfig,
route,
index,
layout,
} from "@react-router/dev/routes";
export const routes: RouteConfig = [
index("./home.tsx"),
route("about", "./about.tsx"),
layout("./auth/layout.tsx", [
route("login", "./auth/login.tsx"),
route("register", "./auth/register.tsx"),
]),
route("concerts", [
index("./concerts/home.tsx"),
route(":city", "./concerts/city.tsx"),
route("trending", "./concerts/trending.tsx"),
]),
];
For Remix consumers migrating to React Router, you can still configure file system routing within routes.ts using the @react-router/fs-routes package. A minimal route config that reproduces the default Remix setup looks like this:
// app/routes.ts
import { type RouteConfig } from "@react-router/dev/routes";
import { flatRoutes } from "@react-router/fs-routes";
export const routes: RouteConfig = flatRoutes();
If you want to migrate from file system routing to config-based routes, you can mix and match approaches by spreading the results of the async flatRoutes function into the array of config-based routes.
// app/routes.ts
import { type RouteConfig, route } from "@react-router/dev/routes";
import { flatRoutes } from "@react-router/fs-routes";
export const routes: RouteConfig = [
// Example config-based route:
route("/hello", "./routes/hello.tsx"),
// File system routes scoped to a different directory:
...(await flatRoutes({
rootDirectory: "fs-routes",
})),
];
If you were using Remix's routes option to use alternative file system routing conventions, you can adapt these to the new RouteConfig format using @react-router/remix-config-routes-adapter.
For example, if you were using Remix v1 route conventions in Remix v2, you can combine @react-router/remix-config-routes-adapter with @remix-run/v1-route-convention to adapt this to React Router:
// app/routes.ts
import { type RouteConfig } from "@react-router/dev/routes";
import { remixConfigRoutes } from "@react-router/remix-config-routes-adapter";
import { createRoutesFromFolders } from "@remix-run/v1-route-convention";
export const routes: RouteConfig = remixConfigRoutes(async (defineRoutes) => {
return createRoutesFromFolders(defineRoutes, {
ignoredFilePatterns: ["**/.*", "**/*.css"],
});
});
Also note that, if you were using Remix's routes option to define config-based routes, you can also adapt these to the new RouteConfig format using @react-router/remix-config-routes-adapter with minimal code changes. While this makes for a fast migration path, we recommend migrating any config-based routes from Remix to the new RouteConfig format since it's a fairly straightforward migration.
// app/routes.ts
-import { type RouteConfig } from "@react-router/dev/routes";
+import { type RouteConfig, route } from "@react-router/dev/routes";
-import { remixConfigRoutes } from "@react-router/remix-config-routes-adapter";
-export const routes: RouteConfig = remixConfigRoutes(async (defineRoutes) => {
- defineRoutes((route) => {
- route("/parent", "./routes/parent.tsx", () => [
- route("/child", "./routes/child.tsx"),
- ]);
- });
-});
+export const routes: RouteConfig = [
+ route("/parent", "./routes/parent.tsx", [
+ route("/child", "./routes/child.tsx"),
+ ]),
+];
React Router now generates types for each of your route modules and passes typed props to route module component exports (#11961, #12019). You can access those types by importing them from ./+types/<route filename without extension>.
See How To > Route Module Type Safety and Explanations > Type Safety for more details.
React Router v7 includes a new prerender config in the vite plugin to support SSG use-cases. This will pre-render your .html and .data files at build time and so you can serve them statically at runtime from a running server or a CDN (#11539)
export default defineConfig({
plugins: [
reactRouter({
async prerender({ getStaticPaths }) {
let slugs = await fakeGetSlugsFromCms();
return [
...getStaticPaths(),
...slugs.map((slug) => `/product/${slug}`),
];
},
}),
tsconfigPaths(),
],
});
async function fakeGetSlugsFromCms() {
await new Promise((r) => setTimeout(r, 1000));
return ["shirt", "hat"];
}
react-router)defer implementation in favor of using raw promises via single fetch and turbo-stream (#11744)
deferAbortedDeferredErrortype TypedDeferredDataUNSAFE_DeferredDataUNSAFE_DEFERRED_SYMBOLreact-router(#11505)
@remix-run/routerreact-router-dom@remix-run/server-runtime@remix-run/testingreact-router-dom package is maintained to ease adoption but it simply re-exports all APIs from react-routerfuture.v7_startTransition flag (#11696)future.v7_normalizeFormMethod future flag (#11697)@remix-run/router
AgnosticDataIndexRouteObjectAgnosticDataNonIndexRouteObjectAgnosticDataRouteMatchAgnosticDataRouteObjectAgnosticIndexRouteObjectAgnosticNonIndexRouteObjectAgnosticRouteMatchAgnosticRouteObjectTrackedPromiseunstable_AgnosticPatchRoutesOnMissFunctionAction -> exported as NavigationType via react-routerRouter exported as RemixRouter to differentiate from RR's <Router>getToPathname (@private)joinPaths (@private)normalizePathname (@private)resolveTo (@private)stripBasename (@private)createBrowserHistory -> in favor of createBrowserRoutercreateHashHistory -> in favor of createHashRoutercreateMemoryHistory -> in favor of createMemoryRoutercreateRoutercreateStaticHandler -> in favor of wrapper createStaticHandler in RR DomgetStaticContextFromErrorreact-router
HashPathnameSearchfuture.v7_prependBasename from the internalized @remix-run/router package (#11726)future.v7_throwAbortReason from internalized @remix-run/router package (#11728)exports field to all packages (#11675)RemixContext to FrameworkContext (#11705)PrefetchPageDescriptor replaced by PageLinkDescriptor (#11960)future.v7_partialHydration flag (#11725)
<RouterProvider fallbackElement> prop
fallbackElement to a hydrateFallbackElement/HydrateFallback on your root routefuture.v7_partialHydration (when using fallbackElement), state.navigation was populated during the initial loadfuture.v7_partialHydration, state.navigation remains in an "idle" state during the initial loadfuture.v7_relativeSplatPath future flag (#11695)v7_skipActionErrorRevalidationv3_fetcherPersist, v3_relativeSplatPath, v3_throwAbortReasoncreateRemixStub to createRoutesStub (#11692)@remix-run/router deprecated detectErrorBoundary option in favor of mapRouteProperties (#11751)react-router/dom subpath export to properly enable react-dom as an optional peerDependency (#11851)
import ReactDOM from "react-dom" in <RouterProvider> in order to access ReactDOM.flushSync(), since that would break createMemoryRouter use cases in non-DOM environmentsreact-router/dom to get the proper component that makes ReactDOM.flushSync() available:
entry.client.tsx:
import { HydratedRouter } from 'react-router/dom'createBrowserRouter/createHashRouter:
import { RouterProvider } from "react-router/dom"future.v7_fetcherPersist flag (#11731)undefined from loaders and actions (#11680, #12057)createRemixRouter/RouterProvider in entry.client instead of RemixBrowser (#11469)json utility (#12146)
Response.json if you still need to construct JSON responses in your app@react-router/*)future.v3_singleFetch flag (#11522)installGlobals() as this should no longer be necessaryexports field to all packages (#11675)react-router through different runtime/adapter packages (#11702)crypto global from the Web Crypto API is now required when using cookie and session APIs
react-router rather than platform-specific packages: (#11837)
createCookiecreateCookieSessionStoragecreateMemorySessionStoragecreateSessionStorageinstallGlobals function from @remix-run/node has been updated to define globalThis.crypto, using Node's require('node:crypto').webcrypto implementationcreateCookieFactorycreateSessionStorageFactorycreateCookieSessionStorageFactorycreateMemorySessionStorageFactory@remix-run/router, @remix-run/server-runtime, and @remix-run/react now that they all live in react-router (#12177)
LoaderFunction, LoaderFunctionArgs, ActionFunction, ActionFunctionArgs, DataFunctionArgs, RouteManifest, LinksFunction, Route, EntryRouteRouteManifest type used by the "remix" code is now slightly stricter because it is using the former @remix-run/router RouteManifest
Record<string, Route> -> Record<string, Route | undefined>AppData type in favor of inlining unknown in the few locations it was usedServerRuntimeMeta* types in favor of the Meta* types they were duplicated fromRoute.* typesRoute.* typesuseFetcher previously had an optional generic (used primarily by Remix v2) that expected the data typetypeof loader/typeof action)useFetcher<LoaderData>()useFetcher<typeof loader>()cookie dependency to ^1.0.1 - please see the release notes for any breaking changes (#12172)@react-router/cloudflare - For Remix consumers migrating to React Router, all exports from @remix-run/cloudflare-pages are now provided for React Router consumers in the @react-router/cloudflare package. There is no longer a separate package for Cloudflare Pages. (#11801)@react-router/cloudflare - The @remix-run/cloudflare-workers package has been deprecated. Remix consumers migrating to React Router should use the @react-router/cloudflare package directly. For guidance on how to use @react-router/cloudflare within a Cloudflare Workers context, refer to the Cloudflare Workers template. (#11801)@react-router/dev - For Remix consumers migrating to React Router, the vitePlugin and cloudflareDevProxyVitePlugin exports have been renamed and moved. (#11904)@react-router/dev - For Remix consumers migrating to React Router who used the Vite plugin's buildEnd hook, the resolved reactRouterConfig object no longer contains a publicPath property since this belongs to Vite, not React Router (#11575)@react-router/dev - For Remix consumers migrating to React Router, the Vite plugin's manifest option has been removed (#11573)@react-router/dev - Update default isbot version to v5 and drop support for isbot@3 (#11770)
isbot@4 or isbot@5 in your package.json:
isbot@3 in your package.json and you have your own entry.server.tsx file in your repo
isbot@5 independent of the React Router v7 upgradeisbot@3 in your package.json and you do not have your own entry.server.tsx file in your repo
isbot@5 in your package.json@react-router/dev - For Remix consumers migrating to React Router, Vite manifests (i.e. .vite/manifest.json) are now written within each build subdirectory, e.g. build/client/.vite/manifest.json and build/server/.vite/manifest.json instead of build/.vite/client-manifest.json and build/.vite/server-manifest.json. This means that the build output is now much closer to what you'd expect from a typical Vite project. (#11573)
build/.vite directory to avoid accidentally serving them in production, particularly from the client build. This was later improved with additional logic that deleted these Vite manifest files at the end of the build process unless Vite's build.manifest had been enabled within the app's Vite config. This greatly reduced the risk of accidentally serving the Vite manifests in production since they're only present when explicitly asked for. As a result, we can now assume that consumers will know that they need to manage these additional files themselves, and React Router can safely generate a more standard Vite build output.react-router - Params, loader data, and action data as props for route component exports (#11961)react-router - Add route module type generation (#12019)react-router - Remove duplicate RouterProvider implementations (#11679)react-router - Stabilize unstable_dataStrategy (#11969)react-router - Stabilize unstable_patchRoutesOnNavigation (#11970)react-router - Add prefetching support to Link/NavLink when using Remix SSR (#11402)react-router - Enhance ScrollRestoration so it can restore properly on an SSR'd document load (#11401)@react-router/dev - Add support for the prerender config in the React Router vite plugin, to support existing SSG use-cases (#11539)@react-router/dev - Remove internal entry.server.spa.tsx implementation which was not compatible with the Single Fetch async hydration approach (#11681)@react-router/serve: Update express.static configurations to support new prerender API (#11547)
build/client/assets folder are served as before, with a 1-year immutable Cache-Control header.html and .data files are not served with a specific Cache-Control header.data files are served with Content-Type: text/x-turbo
express.static, it seems to also add a Cache-Control: public, max-age=0 to .data filessubstr with substring (#12080)react-router - Fix redirects returned from loaders/actions using data() (#12021)@react-router/dev - Enable prerendering for resource routes (#12200)@react-router/dev - resolve config directory relative to flat output file structure (#12187)react-router@react-router/architect@react-router/cloudflare@react-router/dev@react-router/express@react-router/fs-routes@react-router/node@react-router/remix-config-routes-adapter@react-router/serveFull Changelog: v6.28.0...v7.0.0
Date: 2025-05-20
6.29.0 to reduce calls to matchRoutes because it surfaced other issues (#13623)v7_relativeSplatPath is set to false (#13502)Full Changelog: v6.30.0...v6.30.1
Date: 2025-02-27
fetcherKey as a parameter to patchRoutesOnNavigation (#13109)6.29.0 via #12169 that caused issues navigating to hash routes inside splat routes for applications using Lazy Route Discovery (patchRoutesOnNavigation) (#13108)Full Changelog: v6.29.0...v6.30.0
Date: 2025-01-30
signal as a parameter to patchRoutesOnNavigation (#12900)
data() result (#12845)matchRoutes calls when possible (#12169)patchRoutesOnNavigation path param for fetcher calls (#12899)Full Changelog: v6.28.2...v6.29.0
Date: 2025-01-16
key usage when not opted into future.v7_fetcherPersist (#12674)Full Changelog: v6.28.1...v6.28.2
Date: 2024-12-20
false (#12441)Full Changelog: v6.28.0...v6.28.1
Date: 2024-11-06
json/defer in favor of returning raw objects
Full Changelog: v6.27.0...v6.28.0
Date: 2024-10-11
This release stabilizes a handful of "unstable" APIs in preparation for the pending React Router v7 release (see these posts for more info):
unstable_dataStrategy → dataStrategy (createBrowserRouter and friends) (Docs)unstable_patchRoutesOnNavigation → patchRoutesOnNavigation (createBrowserRouter and friends) (Docs)unstable_flushSync → flushSync (useSubmit, fetcher.load, fetcher.submit) (Docs)unstable_viewTransition → viewTransition (<Link>, <Form>, useNavigate, useSubmit) (Docs)unstable_flushSync option for navigations and fetchers (#11989)unstable_viewTransition option for navigations and the corresponding unstable_useViewTransitionState hook (#11989)unstable_dataStrategy (#11974)unstable_patchRoutesOnNavigation (#11973)
PatchRoutesOnNavigationFunctionArgs type for convenience (#11967)?index param already exists from a prior submission (#12003)useFormAction bug - when removing ?index param it would not keep other non-Remix index params (#12003)preventScrollReset through redirects during concurrent fetches (#11999)console.error on fetcher abort due to back-to-back revalidation calls (#12050)partialHydration when hydrating with errors (#12070)patchRoutesOnNavigation calls (#12055)
unstable_ APIpatchRoutesOnNavigation internally so that multiple navigations with the same start/end would only execute the function once and use the same promisepatch short circuiting if a navigation was interrupted (and the request.signal aborted) since the first invocation's patch would no-opimport() for async routes will already be cached automatically - and if not it's easy enough for users to implement this cache in userlanddiscoveredRoutes FIFO queue from unstable_patchRoutesOnNavigation (#11977)
unstable_ APIpatchRoutesOnNavigationRouteObject within PatchRoutesOnNavigationFunction's patch method so it doesn't expect agnostic route objects passed to patch (#11967)patchRoutesOnNavigation directly to useRouteError instead of wrapping them in a 400 ErrorResponse instance (#12111)Full Changelog: v6.26.2...v6.27.0
Date: 2024-09-09
unstable_dataStrategy API to allow for more advanced implementations (#11943)
unstable_dataStrategy, please review carefully as this includes breaking changes to this APIunstable_HandlerResult to unstable_DataStrategyResultunstable_dataStrategy from a parallel array of unstable_DataStrategyResult[] (parallel to matches) to a key/value object of routeId => unstable_DataStrategyResult
match.shouldLoad)handlerOverride instead of returning a DataStrategyResult
handlerOverride will be wrapped up into a DataStrategyResult and returned fromm match.resolvematch.resolve() into a final results object you should not need to think about the DataStrategyResult typehandlerOverride, then you will need to assign a DataStrategyResult as the value so React Router knows if it's a successful execution or an error (see examples in the documentation for details)fetcherKey parameter to unstable_dataStrategy to allow differentiation from navigational and fetcher callsblocker.proceed is called quickly/synchronously (#11930)Full Changelog: v6.26.1...v6.26.2
Date: 2024-08-15
unstable_patchRoutesOnMiss to unstable_patchRoutesOnNavigation to match new behavior (#11888)unstable_patchRoutesOnNavigation logic so that we call the method when we match routes with dynamic param or splat segments in case there exists a higher-scoring static route that we've not yet discovered (#11883)
unstable_patchRoutesOnNavigation against so that we don't re-call on subsequent navigations to the same pathFull Changelog: v6.26.0...v6.26.1
Date: 2024-08-01
replace(url, init?) alternative to redirect(url, init?) that performs a history.replaceState instead of a history.pushState on client-side navigation redirects (#11811)unstable_data() API for usage with Remix Single Fetch (#11836)
createStaticHandler.query() to allow loaders/actions to return arbitrary data along with custom status/headers without forcing the serialization of data into a Response instanceunstable_dataStrategy such as serializing via turbo-stream in Remix Single Fetchstatus field from HandlerResult
status from unstable_dataStrategy you should instead do so via unstable_data()future.v7_partialHydration along with unstable_patchRoutesOnMiss (#11838)
router.state.matches will now include any partial matches so that we can render ancestor HydrateFallback componentsFull Changelog: v6.25.1...v6.26.0
Date: 2024-07-17
RouterProvider internals to reduce unnecessary re-renders (#11803)Full Changelog: v6.25.0...v6.25.1
Date: 2024-07-16
v7_skipActionErrorRevalidationThis release stabilizes the future.unstable_skipActionErrorRevalidation flag into future.v7_skipActionErrorRevalidation in preparation for the upcoming React Router v7 release.
4xx/5xx Response will not trigger a revalidation by defaultshouldRevalidate's unstable_actionStatus parameter to actionStatusfuture.unstable_skipActionErrorRevalidation as future.v7_skipActionErrorRevalidation (#11769)useMatch so matches/params reflect decoded params (#11789)unstable_patchRoutesOnMiss (#11786)unstable_patchRoutesOnMiss that matched a splat route on the server (#11790)Full Changelog: v6.24.1...v6.25.0
Date: 2024-07-03
polyfill.io reference from warning message because the domain was sold and has since been determined to serve malware (#11741)
NavLinkRenderProps type for easier typing of custom NavLink callback (#11553)future.v7_relativeSplatPath, properly resolve relative paths in splat routes that are children of pathless routes (#11633)router.routes identity/reflow during route patching (#11740)Full Changelog: v6.24.0...v6.24.1
Date: 2024-06-24
We're really excited to release our new API for "Lazy Route Discovery" in v6.24.0! For some background information, please check out the original RFC. The tl;dr; is that ever since we introduced the Data APIs in v6.4 via <RouterProvider>, we've been a little bummed that one of the tradeoffs was the lack of a compelling code-splitting story mirroring what we had in the <BrowserRouter>/<Routes> apps. We took a baby-step towards improving that story with route.lazy in v6.9.0, but with v6.24.0 we've gone the rest of the way.
With "Fog of War", you can now load portions of the route tree lazily via the new unstable_patchRoutesOnMiss option passed to createBrowserRouter (and it's memory/hash counterparts). This gives you a way to hook into spots where React Router is unable to match a given path and patch new routes into the route tree during the navigation (or fetcher call).
Here's a very small example, but please refer to the documentation for more information and use cases:
const router = createBrowserRouter(
[
{
id: "root",
path: "/",
Component: RootComponent,
},
],
{
async unstable_patchRoutesOnMiss({ path, patch }) {
if (path === "/a") {
// Load the `a` route (`{ path: 'a', Component: A }`)
let route = await getARoute();
// Patch the `a` route in as a new child of the `root` route
patch("root", [route]);
}
},
},
);
fetcher.submit types - remove incorrect navigate/fetcherKey/unstable_viewTransition options because they are only relevant for useSubmit (#11631)location.state values passed to <StaticRouter> (#11495)Full Changelog: v6.23.1...v6.24.0
Date: 2024-05-10
undefined to be resolved through <Await> (#11513)document check when checking for document.startViewTransition availability (#11544)react-router-dom/server import back to react-router-dom instead of index.ts (#11514)@remix-run/router - Support unstable_dataStrategy on staticHandler.queryRoute (#11515)Full Changelog: v6.23.0...v6.23.1
Date: 2024-04-23
The new unstable_dataStrategy API is a low-level API designed for advanced use-cases where you need to take control over the data strategy for your loader/action functions. The default implementation is today's behavior, to fetch all loaders in parallel, but this option allows users to implement more advanced data flows including Remix "Single Fetch", user-land middleware/context APIs, automatic loader caching, and more. Please see the docs for more information.
Note: This is a low-level API intended for advanced use-cases. This overrides React Router's internal handling of loader/action execution, and if done incorrectly will break your app code. Please use with caution and perform the appropriate testing.
Currently, all active loader's revalidate after any action submission, regardless of the action result. However, in the majority of cases a 4xx/5xx response from an action means that no data was actually changed and the revalidation is unnecessary. We've introduced a new future.unstable_skipActionErrorRevalidation flag that changes the behavior here, and we plan to make this the default in future version of React Router.
With this flag enabled, action's that return/throw a 4xx/5xx response status will no longer automatically revalidate. If you need to revalidate after a 4xx/5xx result with this flag enabled, you can still do that via returning true from shouldRevalidate - which now also receives a new unstable_actionStatus argument alongside actionResult so you can make decision based on the status of the action response without having to encode it into the action data.
unstable_dataStrategy configuration option (#11098, #11377)@remix-run/router - Add a new future.unstable_skipActionRevalidation future flag (#11098)@remix-run/router - SSR: Added a new skipLoaderErrorBubbling options to the staticHandler.query method to disable error bubbling by the static handler for use in Remix's Single Fetch implementation (#11098, (#11377))Full Changelog: v6.22.3...v6.23.0
Date: 2024-03-07
future.v7_partialHydration bug that would re-run loaders below the boundary on hydration if SSR loader errors bubbled to a parent boundary (#11324)future.v7_partialHydration bug that would consider the router uninitialized if a route did not have a loader (#11325)Full Changelog: v6.22.2...v6.22.3
Date: 2024-02-28
Full Changelog: v6.22.1...v6.22.2
Date: 2024-02-16
Full Changelog: v6.22.0...v6.22.1
Date: 2024-02-01
In 2021, the HTTP Archive launched the Core Web Vitals Technology Report dashboard:
By combining the powers of real-user experiences in the Chrome UX Report 26 (CrUX) dataset with web technology detections in HTTP Archive 30, we can get a glimpse into how architectural decisions like choices of CMS platform or JavaScript framework play a role in sites’ CWV performance.
They use a tool called wappalyzer to identify what technologies a given website is using by looking for certain scripts, global JS variables, or other identifying characteristics. For example, for Remix applications, they look for the global __remixContext variable to identify that a website is using Remix.
It was brought to our attention that React Router was unable to be reliably identified because there are no identifying global aspects. They are currently looking for external scripts with react-router in the name. This will identify sites using React Router from a CDN such as unpkg - but it will miss the vast majority of sites that are installing React Router from the npm registry and bundling it into their JS files. This results in drastically under-reporting the usage of React Router on the web.
Starting with version 6.22.0, sites using react-router-dom will begin adding a window.__reactRouterVersion variable that will be set to a string value of the SemVer major version number (i.e., window.__reactRouterVersion = "6";) so that they can be properly identified.
window.__reactRouterVersion for CWV Report detection (#11222)createStaticHandler future.v7_throwAbortReason flag to throw request.signal.reason (defaults to a DOMException) when a request is aborted instead of an Error such as new Error("query() call aborted: GET /path") (#11104)
DOMException was added in Node v17 so you will not get a DOMException on Node 16 and below.ErrorResponse status code if passed to getStaticContextFormError (#11213)Full Changelog: v6.21.3...v6.22.0
Date: 2024-01-18
NavLink isPending when a basename is used (#11195)unstable_ prefix from Blocker/BlockerFunction types (#11187)Full Changelog: v6.21.2...v6.21.3
Date: 2024-01-11
useId for internal fetcher keys when available (#11166)Full Changelog: v6.21.1...v6.21.2
Date: 2023-12-21
route.lazy not working correctly on initial SPA load when v7_partialHydration is specified (#11121)submitting phase (#11102)resolveTo (#11097)Full Changelog: v6.21.0...v6.21.1
Date: 2023-12-13
future.v7_relativeSplatPathWe fixed a splat route path-resolution bug in 6.19.0, but later determined a large number of applications were relying on the buggy behavior, so we reverted the fix in 6.20.1 (see #10983, #11052, #11078).
The buggy behavior is that the default behavior when resolving relative paths inside a splat route would ignore any splat (*) portion of the current route path. When the future flag is enabled, splat portions are included in relative path logic within splat routes.
For more information, please refer to the useResolvedPath docs and/or the detailed changelog entry.
We added a new future.v7_partialHydration future flag for the @remix-run/router that enables partial hydration of a data router when Server-Side Rendering. This allows you to provide hydrationData.loaderData that has values for some initially matched route loaders, but not all. When this flag is enabled, the router will call loader functions for routes that do not have hydration loader data during router.initialize(), and it will render down to the deepest provided HydrateFallback (up to the first route without hydration data) while it executes the unhydrated routes. (#11033)
future.v7_relativeSplatPath flag to implement a breaking bug fix to relative routing when inside a splat route. (#11087)future.v7_partialHydration future flag that enables partial hydration of a data router when Server-Side Rendering (#11033)ErrorBoundary's (#11071)loader/action functions (#11061)relative="path" issue when rendering Link/NavLink outside of matched routes (#11062)Full Changelog: v6.20.1...v6.21.0
Date: 2023-12-01
useResolvedPath fix for splat routes due to a large number of applications that were relying on the buggy behavior (see #11052) (#11078)
6.19.0 and 6.20.0. If you are upgrading from 6.18.0 or earlier, you would not have been impacted by this fix.Full Changelog: v6.20.0...v6.20.1
Date: 2023-11-22
[!WARNING] Please use version
6.20.1or later instead of6.20.0. We discovered that a large number of apps were relying on buggy behavior that was fixed in this release (#11045). We reverted the fix in6.20.1and will be re-introducing it behind a future flag in a subsequent release. See #11052 for more details.
PathParam type from the public API (#10719)v7_fetcherPersist is enabled (#11044)resolveTo path resolution in splat routes (#11045)
getPathContributingMatchesUNSAFE_getPathContributingMatches export from @remix-run/router since we no longer need this in the react-router/react-router-dom layersFull Changelog: v6.19.0...v6.20.0
Date: 2023-11-16
[!WARNING] Please use version
6.20.1or later instead of6.19.0. We discovered that a large number of apps were relying on buggy behavior that was fixed in this release (#10983). We reverted the fix in6.20.1and will be re-introducing it behind a future flag in a subsequent release. See #11052 for more details.
unstable_flushSync APIThis release brings a new unstable_flushSync option to the imperative APIs (useSubmit, useNavigate, fetcher.submit, fetcher.load) to let users opt-into synchronous DOM updates for pending/optimistic UI.
function handleClick() {
submit(data, { flushSync: true });
// Everything is flushed to the DOM so you can focus/scroll to your pending/optimistic UI
setFocusAndOrScrollToNewlyAddedThing();
}
unstable_flushSync option to useNavigate/useSubmit/fetcher.load/fetcher.submit to opt-out of React.startTransition and into ReactDOM.flushSync for state updates (#11005)unstable_ prefix from the useBlocker hook as it's been in use for enough time that we are confident in the API (#10991)
unstable_usePrompt due to differences in how browsers handle window.confirm that prevent React Router from guaranteeing consistent/correct behaviorFix useActionData so it returns proper contextual action data and not any action data in the tree (#11023)
Fix bug in useResolvedPath that would cause useResolvedPath(".") in a splat route to lose the splat portion of the URL path. (#10983)
"." paths inside a splat route which incorrectly dropped the splat portion of the URL. If you are relative routing via "." inside a splat route in your application you should double check that your logic is not relying on this buggy behavior and update accordingly.Fix issue where a changing fetcher key in a useFetcher that remains mounted wasn't getting picked up (#11009)
Fix useFormAction which was incorrectly inheriting the ?index query param from child route action submissions (#11025)
Fix NavLink active logic when to location has a trailing slash (#10734)
Fix types so unstable_usePrompt can accept a BlockerFunction in addition to a boolean (#10991)
Fix relative="path" bug where relative path calculations started from the full location pathname, instead of from the current contextual route pathname. (#11006)
<Route path="/a">
<Route path="/b" element={<Component />}>
<Route path="/c" />
</Route>
</Route>;
function Component() {
return (
<>
{/* This is now correctly relative to /a/b, not /a/b/c */}
<Link to=".." relative="path" />
<Outlet />
</>
);
}
Full Changelog: 6.18.0...6.19.0
Date: 2023-10-31
Per this RFC, we've introduced some new APIs that give you more granular control over your fetcher behaviors.
useFetcher({ key: string }), which allows you to access the same fetcher instance from different components in your application without prop-drillinguseFetchers so that they can be looked up by keyForm and useSubmit now support optional navigate/fetcherKey props/params to allow kicking off a fetcher submission under the hood with an optionally user-specified key
<Form method="post" navigate={false} fetcherKey="my-key">submit(data, { method: "post", navigate: false, fetcherKey: "my-key" })useFetchers() or useFetcher({ key }) to look it up elsewherefuture.v7_fetcherPersist)Per the same RFC as above, we've introduced a new future.v7_fetcherPersist flag that allows you to opt-into the new fetcher persistence/cleanup behavior. Instead of being immediately cleaned up on unmount, fetchers will persist until they return to an idle state. This makes pending/optimistic UI much easier in scenarios where the originating fetcher needs to unmount.
useFetchers() API was always supposed to only reflect in-flight fetcher information for pending/optimistic UI -- it was not intended to reflect fetcher data or hang onto fetchers after they returned to an idle stateuseFetchers() after completion - they served no purpose in there since you can access the data via useFetcher().dataidle state
useFetchers while in-flight so you can still access pending/optimistic data after unmountkey, then it's result will be processed, even if the originating fetcher was unmountedkey APIs and navigate=false options (#10960)future.v7_fetcherPersist flag (#10962)matchPath (#10768)future prop on BrowserRouter, HashRouter and MemoryRouter so that it accepts a Partial<FutureConfig> instead of requiring all flags to be included (#10962)router.getFetcher/router.deleteFetcher type definitions which incorrectly specified key as an optional parameter (#10960)Full Changelog: 6.17.0...6.18.0
Date: 2023-10-16
We're excited to release experimental support for the View Transitions API in React Router! You can now trigger navigational DOM updates to be wrapped in document.startViewTransition to enable CSS animated transitions on SPA navigations in your application.
The simplest approach to enabling a View Transition in your React Router app is via the new <Link unstable_viewTransition> prop. This will cause the navigation DOM update to be wrapped in document.startViewTransition which will enable transitions for the DOM update. Without any additional CSS styles, you'll get a basic cross-fade animation for your page.
If you need to apply more fine-grained styles for your animations, you can leverage the unstable_useViewTransitionState hook which will tell you when a transition is in progress and you can use that to apply classes or styles:
function ImageLink(to, src, alt) {
const isTransitioning = unstable_useViewTransitionState(to);
return (
<Link to={to} unstable_viewTransition>
<img
src={src}
alt={alt}
style={{
viewTransitionName: isTransitioning ? "image-expand" : "",
}}
/>
</Link>
);
}
You can also use the <NavLink unstable_viewTransition> shorthand which will manage the hook usage for you and automatically add a transitioning class to the <a> during the transition:
a.transitioning img {
view-transition-name: "image-expand";
}
<NavLink to={to} unstable_viewTransition>
<img src={src} alt={alt} />
</NavLink>
For an example usage of View Transitions, check out our fork of the awesome Astro Records demo.
For more information on using the View Transitions API, please refer to the Smooth and simple transitions with the View Transitions API guide from the Google Chrome team.
ScrollRestoration when sessionStorage is unavailable (#10848)RouterProvider future prop type to be a Partial<FutureConfig> so that not all flags must be specified (#10900)ErrorResponse type to avoid leaking internal field (#10876)Full Changelog: 6.16.0...6.17.0
Date: 2023-09-13
any with unknown on exposed typings for user-provided data. To do this in Remix v2 without introducing breaking changes in React Router v6, we have added generics to a number of shared types. These continue to default to any in React Router and are overridden with unknown in Remix. In React Router v7 we plan to move these to unknown as a breaking change. (#10843)
Location now accepts a generic for the location.state valueActionFunctionArgs/ActionFunction/LoaderFunctionArgs/LoaderFunction now accept a generic for the context parameter (only used in SSR usages via createStaticHandler)useMatches (now exported as UIMatch) accepts generics for match.data and match.handle - both of which were already set to unknown@private class export ErrorResponse to an UNSAFE_ErrorResponseImpl export since it is an implementation detail and there should be no construction of ErrorResponse instances in userland. This frees us up to export a type ErrorResponse which correlates to an instance of the class via InstanceType. Userland code should only ever be using ErrorResponse as a type and should be type-narrowing via isRouteErrorResponse. (#10811)ShouldRevalidateFunctionArgs interface (#10797)_isFetchActionRedirect, _hasFetcherDoneAnything) (#10715)query/queryRoute calls (#10793)route.lazy routes (#10778)actionResult on the arguments object passed to shouldRevalidate (#10779)Full Changelog: v6.15.0...v6.16.0
Date: 2023-08-10
redirectDocument() function which allows users to specify that a redirect from a loader/action should trigger a document reload (via window.location) instead of attempting to navigate to the redirected location via React Router (#10705)useRevalidator is referentially stable across re-renders if revalidations are not actively occurring (#10707)URLSearchParams and the useSearchParams hook (#10620)unstable_usePrompt to avoid throwing an exception if the prompt is unblocked and a navigation is performed synchronously (#10687, #10718)useFormAction() for unspecified actions since it cannot be determined on the server and causes hydration issues (#10758)queryRoute that was not always identifying thrown Response instances (#10717)react-router-native: Update @ungap/url-search-params dependency from ^0.1.4 to ^0.2.2 (#10590)Full Changelog: v6.14.2...v6.15.0
Date: 2023-07-17
<Form state> prop to populate history.state on submission navigations (#10630)defer promise resolves/rejects with undefined in order to match the behavior of loaders and actions which must return a value or null (#10690)<ScrollRestoration> (#10682)Route.lazy to prohibit returning an empty object (#10634)Error subclasses such as ReferenceError/TypeError (#10633)Full Changelog: v6.14.1...v6.14.2
Date: 2023-06-30
unstable_useBlocker when used with an unstable blocker function (#10652)@remix-run/router@1.7.1Full Changelog: v6.14.0...v6.14.1
Date: 2023-06-23
6.14.0 adds support for JSON and Text submissions via useSubmit/fetcher.submit since it's not always convenient to have to serialize into FormData if you're working in a client-side SPA. To opt-into these encodings you just need to specify the proper formEncType:
Opt-into application/json encoding:
function Component() {
let navigation = useNavigation();
let submit = useSubmit();
submit({ key: "value" }, { method: "post", encType: "application/json" });
// navigation.formEncType => "application/json"
// navigation.json => { key: "value" }
}
async function action({ request }) {
// request.headers.get("Content-Type") => "application/json"
// await request.json() => { key: "value" }
}
Opt-into text/plain encoding:
function Component() {
let navigation = useNavigation();
let submit = useSubmit();
submit("Text submission", { method: "post", encType: "text/plain" });
// navigation.formEncType => "text/plain"
// navigation.text => "Text submission"
}
async function action({ request }) {
// request.headers.get("Content-Type") => "text/plain"
// await request.text() => "Text submission"
}
⚠️ Default Behavior Will Change in v7
Please note that to avoid a breaking change, the default behavior will still encode a simple key/value JSON object into a FormData instance:
function Component() {
let navigation = useNavigation();
let submit = useSubmit();
submit({ key: "value" }, { method: "post" });
// navigation.formEncType => "application/x-www-form-urlencoded"
// navigation.formData => FormData instance
}
async function action({ request }) {
// request.headers.get("Content-Type") => "application/x-www-form-urlencoded"
// await request.formData() => FormData instance
}
This behavior will likely change in v7 so it's best to make any JSON object submissions explicit with formEncType: "application/x-www-form-urlencoded" or formEncType: "application/json" to ease your eventual v7 migration path.
application/json and text/plain encodings for useSubmit/fetcher.submit. To reflect these additional types, useNavigation/useFetcher now also contain navigation.json/navigation.text and fetcher.json/fetcher.text which include the json/text submission if applicable. (#10413)submitter element, prefer the built-in new FormData(form, submitter) instead of the previous manual approach in modern browsers (those that support the new submitter parameter) (#9865)
type="image" buttonsformdata-submitter-polyfillwindow.history.pushState/replaceState before updating React Router state (instead of after) so that window.location matches useLocation during synchronous React 17 rendering (#10448)
window.location and should always reference useLocation when possible, as window.location will not be in sync 100% of the time (due to popstate events, concurrent mode, etc.)shouldRevalidate for fetchers that have not yet completed a data load (#10623)basename from the location provided to <ScrollRestoration getKey> to match the useLocation behavior (#10550)basename from locations provided to unstable_useBlocker functions to match the useLocation behavior (#10573)unstable_useBlocker key issues in StrictMode (#10573)generatePath when passed a numeric 0 value parameter (#10612)tsc --skipLibCheck:false issues on React 17 (#10622)typescript to 5.1 (#10581)Full Changelog: v6.13.0...v6.14.0
Date: 2023-06-14
6.13.0 is really a patch release in spirit but comes with a SemVer minor bump since we added a new future flag.
future.v7_startTransitionThe tl;dr; is that 6.13.0 is the same as 6.12.0 bue we've moved the usage of React.startTransition behind an opt-in future.v7_startTransition future flag because we found that there are applications in the wild that are currently using Suspense in ways that are incompatible with React.startTransition.
Therefore, in 6.13.0 the default behavior will no longer leverage React.startTransition:
<BrowserRouter>
<Routes>{/*...*/}</Routes>
</BrowserRouter>
<RouterProvider router={router} />
If you wish to enable React.startTransition, pass the future flag to your router component:
<BrowserRouter future={{ v7_startTransition: true }}>
<Routes>{/*...*/}</Routes>
</BrowserRouter>
<RouterProvider router={router} future={{ v7_startTransition: true }}/>
We recommend folks adopt this flag sooner rather than later to be better compatible with React concurrent mode, but if you run into issues you can continue without the use of React.startTransition until v7. Issues usually boil down to creating net-new promises during the render cycle, so if you run into issues when opting into React.startTransition, you should either lift your promise creation out of the render cycle or put it behind a useMemo.
React.startTransition usage behinds a future flag (#10596)React.startTransition minification bug in production mode (#10588)Full Changelog: v6.12.1...v6.13.0
Date: 2023-06-08
[!WARNING] Please use version
6.13.0or later instead of6.12.0/6.12.1. These versions suffered from some Webpack build/minification issues resulting failed builds or invalid minified code in your production bundles. See #10569 and #10579 for more details.
React.startTransition to fix webpack + react 17 compilation error (#10569)Full Changelog: v6.12.0...v6.12.1
Date: 2023-06-06
[!WARNING] Please use version
6.13.0or later instead of6.12.0/6.12.1. These versions suffered from some Webpack build/minification issues resulting failed builds or invalid minified code in your production bundles. See #10569 and #10579 for more details.
React.startTransition supportWith 6.12.0 we've added better support for suspending components by wrapping the internal router state updates in React.startTransition. This means that, for example, if one of your components in a destination route suspends and you have not provided a Suspense boundary to show a fallback, React will delay the rendering of the new UI and show the old UI until that asynchronous operation resolves. This could be useful for waiting for things such as waiting for images or CSS files to load (and technically, yes, you could use it for data loading but we'd still recommend using loaders for that 😀). For a quick overview of this usage, check out Ryan's demo on Twitter.
React.startTransition (#10438)DOMException (DataCloneError) when attempting to perform a PUSH navigation with non-serializable state. (#10427)jest and jsdom (#10453)@remix-run/router@1.6.3 (Changelog)Full Changelog: v6.11.2...v6.12.0
Date: 2023-05-17
basename duplication in descendant <Routes> inside a <RouterProvider> (#10492)SetURLSearchParams type (#10444)manifest in _internalSetRoutes (#10437)Full Changelog: v6.11.1...v6.11.2
Date: 2023-05-03
Component API within descendant <Routes> (#10434)useNavigate from <Routes> inside a <RouterProvider> (#10432)<Navigate> in strict mode when using a data router (#10435)basename handling when navigating without a path (#10433)/path#hash -> /path#hash) (#10408)Full Changelog: v6.11.0...v6.11.1
Date: 2023-04-28
basename support in useFetcher (#10336)
basename then you will need to remove the manually prepended basename from your fetcher calls (fetcher.load('/basename/route') -> fetcher.load('/route'))@remix-run/router@1.6.0 (Changelog)RouterProvider, useNavigate/useSubmit/fetcher.submit are now stable across location changes, since we can handle relative routing via the @remix-run/router instance and get rid of our dependence on useLocation() (#10336)
BrowserRouter, these hooks remain unstable across location changes because they still rely on useLocation()action submissions or router.revalidate calls (#10344)Component instead of element on a route definition (#10287)<Link to="//"> and other invalid URL values (#10367)useSyncExternalStore to useState for internal @remix-run/router router state syncing in <RouterProvider>. We found some subtle bugs where router state updates got propagated before other normal useState updates, which could lead to foot guns in useEffect calls. (#10377, #10409)<Routes> when RouterProvider errors existed (#10374)useNavigate in the render cycle by setting the activeRef in a layout effect, allowing the navigate function to be passed to child components and called in a useEffect there (#10394)useRevalidator() to resolve a loader-driven error boundary scenario (#10369)LoaderFunction/ActionFunction return type to prevent undefined from being a valid return value (#10267)fetcher.load call to a route without a loader (#10345)AbortController usage between revalidating fetchers and the thing that triggered them such that the unmount/deletion of a revalidating fetcher doesn't impact the ongoing triggering navigation/revalidation (#10271)Full Changelog: v6.10.0...v6.11.0
Date: 2023-03-29
We recently published a post over on the Remix Blog titled "Future Proofing Your Remix App" that goes through our strategy to ensure smooth upgrades for your Remix and React Router apps going forward. React Router 6.10.0 adds support for these flags (for data routers) which you can specify when you create your router:
const router = createBrowserRouter(routes, {
future: {
// specify future flags here
},
});
You can also check out the docs here and here.
future.v7_normalizeFormMethodThe first future flag being introduced is future.v7_normalizeFormMethod which will normalize the exposed useNavigation()/useFetcher() formMethod fields as uppercase HTTP methods to align with the fetch() (and some Remix) behavior. (#10207)
future.v7_normalizeFormMethod is unspecified or set to false (default v6 behavior),
useNavigation().formMethod is lowercaseuseFetcher().formMethod is lowercasefuture.v7_normalizeFormMethod === true:
useNavigation().formMethod is UPPERCASEuseFetcher().formMethod is UPPERCASEcreateStaticHandler to also check for ErrorBoundary on routes in addition to errorElement (#10190)createRoutesFromElements (#10193)shouldRevalidate if the fetcher action redirects (#10208)lazy() errors during router initialization (#10201)instanceof check for DeferredData to be resilient to ESM/CJS boundaries in SSR bundling scenarios (#10247)@remix-run/web-fetch@4.3.3 (#10216)Full Changelog: v6.9.0...v6.10.0
Date: 2023-03-10
Component/ErrorBoundary route propertiesReact Router now supports an alternative way to define your route element and errorElement fields as React Components instead of React Elements. You can instead pass a React Component to the new Component and ErrorBoundary fields if you choose. There is no functional difference between the two, so use whichever approach you prefer 😀. You shouldn't be defining both, but if you do Component/ErrorBoundary will "win"
Example JSON Syntax
// Both of these work the same:
const elementRoutes = [{
path: '/',
element: <Home />,
errorElement: <HomeError />,
}]
const componentRoutes = [{
path: '/',
Component: Home,
ErrorBoundary: HomeError,
}]
function Home() { ... }
function HomeError() { ... }
Example JSX Syntax
// Both of these work the same:
const elementRoutes = createRoutesFromElements(
<Route path='/' element={<Home />} errorElement={<HomeError /> } />
);
const componentRoutes = createRoutesFromElements(
<Route path='/' Component={Home} ErrorBoundary={HomeError} />
);
function Home() { ... }
function HomeError() { ... }
In order to keep your application bundles small and support code-splitting of your routes, we've introduced a new lazy() route property. This is an async function that resolves the non-route-matching portions of your route definition (loader, action, element/Component, errorElement/ErrorBoundary, shouldRevalidate, handle).
Lazy routes are resolved on initial load and during the loading or submitting phase of a navigation or fetcher call. You cannot lazily define route-matching properties (path, index, children) since we only execute your lazy route functions after we've matched known routes.
Your lazy functions will typically return the result of a dynamic import.
// In this example, we assume most folks land on the homepage so we include that
// in our critical-path bundle, but then we lazily load modules for /a and /b so
// they don't load until the user navigates to those routes
let routes = createRoutesFromElements(
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="a" lazy={() => import("./a")} />
<Route path="b" lazy={() => import("./b")} />
</Route>,
);
Then in your lazy route modules, export the properties you want defined for the route:
export async function loader({ request }) {
let data = await fetchData(request);
return json(data);
}
// Export a `Component` directly instead of needing to create a React Element from it
export function Component() {
let data = useLoaderData();
return (
<>
<h1>You made it!</h1>
<p>{data}</p>
</>
);
}
// Export an `ErrorBoundary` directly instead of needing to create a React Element from it
export function ErrorBoundary() {
let error = useRouteError();
return isRouteErrorResponse(error) ? (
<h1>
{error.status} {error.statusText}
</h1>
) : (
<h1>{error.message || error}</h1>
);
}
An example of this in action can be found in the examples/lazy-loading-router-provider directory of the repository. For more info, check out the lazy docs.
🙌 Huge thanks to @rossipedia for the Initial Proposal and POC Implementation.
route.Component/route.ErrorBoundary properties (#10045)route.lazy (#10045)generatePath incorrectly applying parameters in some cases (#10078)[react-router-dom-v5-compat] Add missed data router API re-exports (#10171)Full Changelog: v6.8.2...v6.9.0
Date: 2023-02-27
<Link to> as external if they are outside of the router basename (#10135)basename (#10076)<Link to> urls (#10112)StaticRouterProvider serialized hydration data (#10068)useBlocker to return IDLE_BLOCKER during SSR (#10046)defer loader responses in createStaticHandler's query() method (#10077)invariant to an UNSAFE_invariant export since it's only intended for internal use (#10066)Full Changelog: v6.8.1...v6.8.2
Date: 2023-02-06
Link component (now also supports mailto: urls) (#9994)Full Changelog: v6.8.0...v6.8.1
Date: 2023-01-26
Support absolute URLs in <Link to>. If the URL is for the current origin, it will still do a client-side navigation. If the URL is for a different origin then it will do a fresh document request for the new origin. (#9900)
<Link to="https://neworigin.com/some/path"> {/* Document request */}
<Link to="//neworigin.com/some/path"> {/* Document request */}
<Link to="https://www.currentorigin.com/path"> {/* Client-side navigation */}
shouldRevalidate calls (#9948)
shouldRevalidate function was only being called for explicit revalidation scenarios (after a mutation, manual useRevalidator call, or an X-Remix-Revalidate header used for cookie setting in Remix). It was not properly being called on implicit revalidation scenarios that also apply to navigation loader revalidation, such as a change in search params or clicking a link for the page we're already on. It's now correctly called in those additional scenarios.current*/next* parameters reflected the static fetcher.load URL (and thus were identical). Instead, they should have reflected the navigation that triggered the revalidation (as the form* parameters did). These parameters now correctly reflect the triggering navigation.useSearchParams (#9969)preventScrollReset on <fetcher.Form> (#9963)pagehide instead of beforeunload for <ScrollRestoration>. This has better cross-browser support, specifically on Mobile Safari. (#9945)instanceof check from isRouteErrorResponse to avoid bundling issues on the server (#9930)defer call only contains critical data and remove the AbortController (#9965)File FormData entries (#9867)react-router-dom-v5-compat - Fix SSR useLayoutEffect console.error when using CompatRouter (#9820)Full Changelog: v6.7.0...v6.8.0
Date: 2023-01-18
unstable_useBlocker/unstable_usePrompt hooks for blocking navigations within the app's location origin (#9709, #9932)preventScrollReset prop to <Form> (#9886)useBeforeUnload (#9709)generatePath when optional params are present (#9764)<Await> to accept ReactNode as children function return result (#9896)jsdom bug workaround in tests (#9824)Full Changelog: v6.6.2...v6.7.0
Date: 2023-01-09
useId consistency during SSR (#9805)Full Changelog: v6.6.1...v6.6.2
Date: 2022-12-23
shouldRevalidate on action redirects (#9777, #9782)actionData on action redirect to current location (#9772)Full Changelog: v6.6.0...v6.6.1
Date: 2022-12-21
This minor release is primarily to stabilize our SSR APIs for Data Routers now that we've wired up the new RouterProvider in Remix as part of the React Router-ing Remix work.
unstable_ prefix from createStaticHandler/createStaticRouter/StaticRouterProvider (#9738)useBeforeUnload() hook (#9664)<Form method> and useSubmit method values (#9664)<button formmethod> form submission overriddes (#9664)replace on submissions and PUSH on submission to new paths (#9734)useLoaderData usage in errorElement (#9735)Error objects from StaticRouterProvider (#9664)hydrationData (#9664)Full Changelog: v6.5.0...v6.6.0
Date: 2022-12-16
This release introduces support for Optional Route Segments. Now, adding a ? to the end of any path segment will make that entire segment optional. This works for both static segments and dynamic parameters.
Optional Params Examples
<Route path=":lang?/about> will match:
/:lang/about/about<Route path="/multistep/:widget1?/widget2?/widget3?"> will match:
/multistep/multistep/:widget1/multistep/:widget1/:widget2/multistep/:widget1/:widget2/:widget3Optional Static Segment Example
<Route path="/home?"> will match:
//home<Route path="/fr?/about"> will match:
/about/fr/about<Route path="prefix-:param">, to align with how splat parameters work. If you were previously relying on this behavior then it's recommended to extract the static portion of the path at the useParams call site: (#9506)// Old behavior at URL /prefix-123
<Route path="prefix-:id" element={<Comp /> }>
function Comp() {
let params = useParams(); // { id: '123' }
let id = params.id; // "123"
...
}
// New behavior at URL /prefix-123
<Route path=":id" element={<Comp /> }>
function Comp() {
let params = useParams(); // { id: 'prefix-123' }
let id = params.id.replace(/^prefix-/, ''); // "123"
...
}
headers on loader request's after SSR document action request (#9721)Full Changelog: v6.4.5...v6.5.0
Date: 2022-12-07
GET request (#9680)instanceof Response checks in favor of isResponse (#9690)URL creation in Cloudflare Pages or other non-browser-environments (#9682, #9689)requestContext support to static handler query/queryRoute (#9696)
queryRoute(path, routeId) has been changed to queryRoute(path, { routeId, requestContext })Full Changelog: v6.4.4...v6.4.5
Date: 2022-11-30
action/loader function returns undefined as revalidations need to know whether the loader has previously been executed. undefined also causes issues during SSR stringification for hydration. You should always ensure your loader/action returns a value, and you may return null if you don't wish to return anything. (#9511)basename in static data routers (#9591)ErrorResponse bodies to contain more descriptive text in internal 403/404/405 scenariosNavLink and descendant <Routes> (#9589, #9647)ErrorResponse instances when using built-in hydration (#9593)basename in static data routers (#9591)@remix-run/router@1.0.4react-router@6.4.4Full Changelog: v6.4.3...v6.4.4
Date: 2022-11-01
<a href> values when using createHashRouter (#9409)formAction pathnames when an index route also has a path (#9486)relative=path prop on NavLink (#9453)NavLink behavior for root urls (#9497)useRoutes should be able to return null when passing locationArg (#9485)initialEntries type in createMemoryRouter (#9498)basename and relative routing in loader/action redirects (#9447)action function (#9455)@remix-run/router (#9446)createURL in local file execution in Firefox (#9464)Full Changelog: v6.4.2...v6.4.3
Date: 2022-10-06
basename in useFormAction (#9352)IndexRouteObject and NonIndexRouteObject types to make hasErrorElement optional (#9394)RouteObject/RouteProps types to surface the error in TypeScript. (#9366)Full Changelog: v6.4.1...v6.4.2
Date: 2022-09-22
initialEntries (#9288)?index for fetcher get submissions to index routes (#9312)Full Changelog: v6.4.0...v6.4.1
Date: 2022-09-13
Whoa this is a big one! 6.4.0 brings all the data loading and mutation APIs over from Remix. Here's a quick high level overview, but it's recommended you go check out the docs, especially the feature overview and the tutorial.
New react-router APIs
createMemoryRouter<RouterProvider>loader and mutate with a Route actionerrorElementdefer and AwaitNew react-router-dom APIs
createBrowserRouter/createHashRouter<Form> componentuseFetcher()defer and Await<ScrollRestoration><Link relative="path"> (#9160)useLocation returns the scoped location inside a <Routes location> component (#9094)<Link replace> prop if it is defined (#8779)Full Changelog: v6.3.0...v6.4.0
Date: 2022-03-31
Full Changelog: v6.2.2...v6.3.0
Date: 2022-02-28
Full Changelog: v6.2.1...v6.2.2
Date: 2021-12-17
history dependency to 5.2.0.Full Changelog: v6.2.0...v6.2.1
Date: 2021-12-17
RouteProps element type, which should be a ReactNode (#8473)useOutlet for top-level routes (#8483)Full Changelog: v6.1.1...v6.2.0
Date: 2021-12-11
HistoryRouter as unstable_HistoryRouter, as this API will likely need to change before a new major release.Full Changelog: v6.1.0...v6.1.1
Date: 2021-12-10
<Outlet> can now receive a context prop. This value is passed to child routes and is accessible via the new useOutletContext hook. See the API docs for details. (#8461)<NavLink> can now receive a child function for access to its props. (#8164)useMatch and matchPath. For example, when you call useMatch("foo/:bar/:baz"), the path is parsed and the return type will be PathMatch<"bar" | "baz">. (#8030)Full Changelog: v6.0.2...v6.1.0
Date: 2021-11-09
reloadDocument prop to <Link>. This allows <Link> to function like a normal anchor tag by reloading the document after navigation while maintaining the relative to resolution (#8283)Full Changelog: v6.0.1...v6.0.2
Date: 2021-11-05
<StaticRouter location> value (#8243)<Route> inside <Routes> to help people make the change (#8238)Full Changelog: v6.0.0...v6.0.1
Date: 2021-11-03
React Router v6 is here!
Please go read our blog post for more information on all the great stuff in v6 including notes about how to upgrade from React Router v5 and Reach Router.