Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

fix(deps): update react-router monorepo to v7 (major)#174

New issue

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

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

Already on GitHub?Sign in to your account

Open
renovate wants to merge1 commit intomaster
base:master
Choose a base branch
Loading
fromrenovate/major-react-router-monorepo

Conversation

@renovate
Copy link
Contributor

@renovaterenovatebot commentedNov 22, 2024
edited
Loading

This PR contains the following updates:

PackageChangeAgeConfidence
react-router (source)4.4.0-beta.8 ->7.9.5ageconfidence
react-router-dom (source)4.4.0-beta.8 ->7.9.5ageconfidence

Release Notes

remix-run/react-router (react-router)

v7.9.5

Compare Source

Patch Changes
  • Move RSCHydratedRouter and utils to/dom export. (#​14457)

  • useRoute: return type-safehandle (#​14462)

    For example:

    // app/routes/admin.tsxconsthandle={hello:"world"};
    // app/routes/some-other-route.tsxexportdefaultfunctionComponent(){constadmin=useRoute("routes/admin");if(!admin)thrownewError("Not nested within 'routes/admin'");console.log(admin.handle);//                ^? { hello: string }}
  • Ensure action handlers run for routes with middleware even if no loader is present (#​14443)

  • Addunstable_instrumentations API to allow users to add observablity to their apps by instrumenting route loaders, actions, middlewares, lazy, as well as server-side request handlers and client side navigations/fetches (#​14412)

    • Framework Mode:
      • entry.server.tsx:export const unstable_instrumentations = [...]
      • entry.client.tsx:<HydratedRouter unstable_instrumentations={[...]} />
    • Data Mode
      • createBrowserRouter(routes, { unstable_instrumentations: [...] })

    This also adds a newunstable_pattern parameter to loaders/actions/middleware which contains the un-interpolated route pattern (i.e.,/blog/:slug) which is useful for aggregating performance metrics by route

v7.9.4

Compare Source

Patch Changes
  • handle external redirects in from server actions (#​14400)

  • New (unstable)useRoute hook for accessing data from specific routes (#​14407)

    For example, let's say you have anadmin route somewhere in your app and you want any child routes ofadmin to all have access to theloaderData andactionData fromadmin.

    // app/routes/admin.tsximport{Outlet}from"react-router";exportconstloader=()=>({message:"Hello, loader!"});exportconstaction=()=>({count:1});exportdefaultfunctionComponent(){return(<div>{/* ... */}<Outlet/>{/* ... */}</div>);}

    You might even want to create a reusable widget that all of the routes nested underadmin could use:

    import{unstable_useRouteasuseRoute}from"react-router";exportfunctionAdminWidget(){// 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:

    exportfunctionAdminWidget(){constadmin=useRoute("routes/dmin");//                      ^^^^^^^^^^^}

    useRoute returnsundefined if the route is not part of the current page:

    exportfunctionAdminWidget(){constadmin=useRoute("routes/admin");if(!admin){thrownewError(`AdminWidget used outside of "routes/admin"`);}}

    Note: theroot route is the exception since it is guaranteed to be part of the current page.
    As a result,useRoute never returnsundefined forroot.

    loaderData andactionData are marked as optional since they could be accessed before theaction is triggered or after theloader threw an error:

    exportfunctionAdminWidget(){constadmin=useRoute("routes/admin");if(!admin){thrownewError(`AdminWidget used outside of "routes/admin"`);}const{ loaderData, actionData}=admin;console.log(loaderData);//          ^? { message: string } | undefinedconsole.log(actionData);//          ^? { count: number } | undefined}

    If instead of a specific route, you wanted access to thecurrent route'sloaderData andactionData, you can calluseRoute without arguments:

    exportfunctionAdminWidget(){constcurrentRoute=useRoute();currentRoute.loaderData;currentRoute.actionData;}

    This usage is equivalent to callinguseLoaderData anduseActionData, but consolidates all route data access into one hook:useRoute.

    Note: when callinguseRoute() (without a route ID), TS has no way to know which route is the current route.
    As a result,loaderData andactionData are typed asunknown.
    If you want more type-safety, you can either narrow the type yourself with something likezod or you can refactor your app to pass down typed props to yourAdminWidget:

    exportfunctionAdminWidget({  message,  count,}:{message:string;count:number;}){/* ... */}

v7.9.3

Compare Source

Patch Changes
  • Do not try to useturbo-stream to decode CDN errors that never reached the server (#​14385)

    • We used to do this but lost this check with the adoption of single fetch
  • Fix Data Mode regression causing a 404 during initial load in whenmiddleware exists without anyloader functions (#​14393)

v7.9.2

Compare Source

Patch Changes
    • Update client-side router to run clientmiddleware on initial load even if no loaders exist (#​14348)
    • UpdatecreateRoutesStub to run route middleware
      • You will need to set the<RoutesStub future={{ v8_middleware: true }} /> flag to enable the propercontext type
  • Update Lazy Route Discovery manifest requests to use a singular comma-separatedpaths query param instead of repeatedp query params (#​14321)

    • This is because Cloudflare has a hard limit of 100 URL search param key/value pairs when used as a key for caching purposes
    • If more that 100 paths were included, the cache key would be incomplete and could produce false-positive cache hits
  • [UNSTABLE] Addfetcher.unstable_reset() API (#​14206)

  • Made useOutlet element reference have stable identity in-between route chages (#​13382)

  • feat: enable full transition support for the rsc router (#​14362)

  • In RSC Data Mode, handle SSR'd client errors and re-try in the browser (#​14342)

  • Supportmiddleware prop on<Route> for usage with a data router viacreateRoutesFromElements (#​14357)

  • Handle encoded question mark and hash characters in ancestor splat routes (#​14249)

  • Fail gracefully on manifest version mismatch logic ifsessionStorage access is blocked (#​14335)

v7.9.1

Compare Source

Patch Changes
  • Fix internalFuture interface naming frommiddleware ->v8_middleware (#​14327)

v7.9.0

Compare Source

Minor Changes
Patch Changes
  • Escape HTML inmeta() JSON-LD content (#​14316)
  • Add react-server Await component implementation (#​14261)
  • In RSC Data Mode when using a custom basename, fix hydration errors for routes that only have client loaders (#​14264)
  • Makehref function available in a react-server context (#​14262)
  • decode each timegetPayload() is called to allow for "in-context" decoding and hoisting of contextual assets (#​14248)
  • href() now correctly processes routes that have an extension after the parameter or are a single optional parameter. (#​13797)

v7.8.2

Compare Source

Patch Changes
  • [UNSTABLE] Remove Data Modefuture.unstable_middleware flag fromcreateBrowserRouter (#​14213)

    • This is only needed as a Framework Mode flag because of the route modules and thegetLoadContext type behavior change
    • In Data Mode, it's an opt-in feature because it's just a new property on a route object, so there's no behavior changes that necessitate a flag
  • [UNSTABLE] Add<RouterProvider unstable_onError>/<HydratedRouter unstable_onError> prop for client side error reporting (#​14162)

  • server action revalidation opt out via $SKIP_REVALIDATION field (#​14154)

  • Properly escape interpolated param values ingeneratePath() (#​13530)

  • MaintainReadonlyMap andReadonlySet types in server response data. (#​13092)

  • [UNSTABLE] Delay serialization of.data redirects to 202 responses until after middleware chain (#​14205)

  • FixTypeError if you throw frompatchRoutesOnNavigation when no partial matches exist (#​14198)

  • Fixbasename usage without a leading slash in data routers (#​11671)

  • [UNSTABLE] Update client middleware so it returns the data strategy results allowing for more advanced post-processing middleware (#​14151)

v7.8.1

Compare Source

Patch Changes
  • Fix usage of optional path segments in nested routes defined using absolute paths (#​14135)
  • Bubble client pre-next middleware error to the shallowest ancestor that needs to load, not strictly the shallowest ancestor with a loader (#​14150)
  • Fix optional static segment matching inmatchPath (#​11813)
  • Fix prerendering when abasename is set withssr:false (#​13791)
  • ProvideisRouteErrorResponse utility inreact-server environments (#​14166)
  • Propagate non-redirect Responses thrown from middleware to the error boundary on document/data requests (#​14182)
  • Handlemeta andlinks Route Exports in RSC Data Mode (#​14136)
  • Properly convert returned/throwndata() values toResponse instances viaResponse.json() in resource routes and middleware (#​14159,#​14181)

v7.8.0

Compare Source

Minor Changes
  • Addnonce prop toLinks &PrefetchPageLinks (#​14048)
  • AddloaderData arguments/properties alongside existingdata arguments/properties to provide consistency and clarity betweenloaderData andactionData across the board (#​14047)
    • Updated types:Route.MetaArgs,Route.MetaMatch,MetaArgs,MetaMatch,Route.ComponentProps.matches,UIMatch
    • @deprecated warnings have been added to the existingdata properties to point users to newloaderData properties, in preparation for removing thedata properties in a future major release
Patch Changes
  • Prevent"Did not find corresponding fetcher result" console error when navigating during afetcher.submit revalidation (#​14114)

  • Bubble client-side middleware errors prior tonext to the appropriate ancestor error boundary (#​14138)

  • Switch Lazy Route Discovery manifest URL generation to usea standaloneURLSearchParams instance instead ofURL.searchParams to avoid a major performance bottleneck in Chrome (#​14084)

  • Adjust internal RSC usage ofReact.use to avoid Webpack compilation errors when using React 18 (#​14113)

  • Remove dependency on@types/node in TypeScript declaration files (#​14059)

  • Fix types forUIMatch to reflect that theloaderData/data properties may beundefined (#​12206)

    • When anErrorBoundary is being rendered, not all active matches will have loader data available, since it may have been theirloader that threw to trigger the boundary
    • TheUIMatch.data type was not correctly handing this and would always reflect the presence of data, leading to the unexpected runtime errors when anErrorBoundary was rendered
    • ⚠️ This may cause some type errors to show up in your code for unguardedmatch.data accesses - you should properly guard forundefined values in those scenarios.
    // app/root.tsxexportfunctionloader(){someFunctionThatThrows();// ❌ Throws an Errorreturn{title:"My Title"};}exportfunctionLayout({ children}:{children:React.ReactNode}){letmatches=useMatches();letrootMatch=matches[0]asUIMatch<Awaited<ReturnType<typeofloader>>>;//  ^ rootMatch.data is 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>;}
  • [UNSTABLE] Ensure resource route errors go throughhandleError w/middleware enabled (#​14078)

  • [UNSTABLE] Propagate returned Response from server middleware if next wasn't called (#​14093)

  • [UNSTABLE] Allow server middlewares to returndata() values which will be converted into aResponse (#​14093)

  • [UNSTABLE] Update middleware error handling so that thenext function never throws and instead handles any middleware errors at the properErrorBoundary and returns theResponse up through the ancestornext function (#​14118)

  • [UNSTABLE] When middleware is enabled, make thecontext parameter read-only (viaReadonly<unstable_RouterContextProvider>) so that TypeScript will not allow you to write arbitrary fields to it in loaders, actions, or middleware. (#​14097)

  • [UNSTABLE] Rename and alter the signature/functionality of theunstable_respond API instaticHandler.query/staticHandler.queryRoute (#​14103)

    • The API has been renamed tounstable_generateMiddlewareResponse for clarity
    • The main functional change is that instead of running the loaders/actions before callingunstable_respond and handing you the result, we now pass aquery/queryRoute function as a parameter and you execute the loaders/actions inside your callback, giving you full access to pre-processing and error handling
    • Thequery version of the API now has a signature of(query: (r: Request) => Promise<StaticHandlerContext | Response>) => Promise<Response>
    • ThequeryRoute 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 callingquery and direct error handling of errors thrown from query
    • ⚠️ This is a breaking change if you've adopted thestaticHandlerunstable_respond API
    letresponse=awaitstaticHandler.query(request,{requestContext:newunstable_RouterContextProvider(),asyncunstable_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 middlewareletresult=awaitquery(request);if(isResponse(result)){returnresult;// Redirects, etc.}returnawaitgenerateHtmlResponse(result);}catch(error:unknown){returngenerateErrorResponse(error);}},});
  • [UNSTABLE] Convert internal middleware implementations to use the newunstable_generateMiddlewareResponse API (#​14103)

  • [UNSTABLE] ChangegetLoadContext signature (type GetLoadContextFunction) whenfuture.unstable_middleware is enabled so that it returns anunstable_RouterContextProvider instance instead of aMap used to contruct the instance internally (#​14097)

    • This also removes thetype unstable_InitialContext export
    • ⚠️ This is a breaking change if you have adopted middleware and are using a custom server with agetLoadContext function
  • [UNSTABLE] Run client middleware on client navigations even if no loaders exist (#​14106)

  • [UNSTABLE] Change theunstable_getContext signature onRouterProvider/HydratedRouter/unstable_RSCHydratedRouter so that it returns anunstable_RouterContextProvider instance instead of aMap used to contruct the instance internally (#​14097)

    • ⚠️ This is a breaking change if you have adopted theunstable_getContext prop
  • [UNSTABLE] proxy server action side-effect redirects from actions for document and callServer requests (#​14131)

  • [UNSTABLE] Fix RSC Data Mode issue where routes that returnfalse fromshouldRevalidate would be replaced by an<Outlet /> (#​14071)

v7.7.1

Compare Source

Patch Changes
  • In RSC Data Mode, fix bug where routes with errors weren't forced to revalidate whenshouldRevalidate returned false (#​14026)
  • In RSC Data Mode, fixMatched leaf route at location "/..." does not have an element or Component warnings when error boundaries are rendered. (#​14021)

v7.7.0

Compare Source

Minor Changes
Patch Changes
  • HandleInvalidCharacterError when validating cookie signature (#​13847)

  • Pass a copy ofsearchParams to thesetSearchParams callback function to avoid muations of the internalsearchParams instance. This was an issue when navigations were blocked because the internal instance be out of sync withuseLocation().search. (#​12784)

  • Support invalidDate inturbo-stream v2 fork (#​13684)

  • In Framework Mode, clear critical CSS in development after initial render (#​13872)

  • Strip search parameters frompatchRoutesOnNavigationpath param for fetcher calls (#​13911)

  • Skip scroll restoration on useRevalidator() calls because they're not new locations (#​13671)

  • Support unencoded UTF-8 routes in prerender config withssr set tofalse (#​13699)

  • Do not throw if the url hash is not a valid URI component (#​13247)

  • Fix a regression increateRoutesStub 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 priorAppLoadContext API. This permittedcreateRoutesStub to work if you were opting into middleware and the updatedcontext typings, but brokecreateRoutesStub 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.

    // If you have not opted into middleware, the old API should work againletcontext:AppLoadContext={/*...*/};letStub=createRoutesStub(routes,context);// If you have opted into middleware, you should now pass an instantiated `unstable_routerContextProvider` instead of a `getContext` factory function.letcontext=newunstable_RouterContextProvider();context.set(SomeContext,someValue);letStub=createRoutesStub(routes,context);

    ⚠️ This may be a breaking bug for if you have adopted the unstable Middleware feature and are usingcreateRoutesStub with the updated API.

  • RemoveContent-Length header from Single Fetch responses (#​13902)

v7.6.3

Compare Source

Patch Changes
  • Do not serialize types foruseRouteLoaderData<typeof clientLoader> (#​13752)

    For types to distinguish aclientLoader from aserverLoader, you MUST annotateclientLoader args:

    //                                   👇 annotation required to skip serializing typesexportfunctionclientLoader({}:Route.ClientLoaderArgs){return{fn:()=>"earth"};}functionSomeComponent(){constdata=useRouteLoaderData<typeofclientLoader>("routes/this-route");constplanet=data?.fn()??"world";return<h1>Hello,{planet}!</h1>;}

v7.6.2

Compare Source

Patch Changes
  • Avoid additionalwith-props chunk in Framework Mode by moving route module component prop logic from the Vite plugin toreact-router (#​13650)
  • Slight refactor of internalheaders() function processing for use with RSC (#​13639)

v7.6.1

Compare Source

Patch Changes
  • UpdateRoute.MetaArgs to reflect thatdata can be potentiallyundefined (#​13563)

    This is primarily for cases where a routeloader threw an error to it's ownErrorBoundary. but it also arises in the case of a 404 which renders the rootErrorBoundary/meta but the root loader did not run because not routes matched.

  • Partially revert optimization added in7.1.4 to reduce calls tomatchRoutes because it surfaced other issues (#​13562)

  • Fix typegen when same route is used at multiple paths (#​13574)

    For example,routes/route.tsx is used at 4 different paths here:

    import{typeRouteConfig,route}from"@&#8203;react-router/dev/routes";exportdefault[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"}),]satisfiesRouteConfig;

    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.

  • Better types forparams (#​13543)

    For example:

    // routes.tsimport{typeRouteConfig,route}from"@&#8203;react-router/dev/routes";exportdefault[route("parent/:p","routes/parent.tsx",[route("layout/:l","routes/layout.tsx",[route("child1/:c1a/:c1b","routes/child1.tsx"),route("child2/:c2a/:c2b","routes/child2.tsx"),]),]),]satisfiesRouteConfig;

    Previously,params for theroutes/layout.tsx route were calculated as{ p: string, l: string }.
    This incorrectly ignores params that could come from child routes.
    If visiting/parent/1/layout/2/child1/3/4, the actual params passed toroutes/layout.tsx will have a type of{ p: string, l: 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// l: string// c1a?: string// c1b?: string// c2a?: string// c2b?: string

    You can also narrow the types forparams as it is implemented as a normalized union of params for each page that includesroutes/layout.tsx:

    if(typeofparams.c1a==='string'){params.|//     ^ cursor is here and you ask for autocompletion// p: string// l: string// c1a: string// c1b: string}

    UNSTABLE: renamed internalreact-router/route-module export toreact-router/internal
    UNSTABLE: removedInfo export from generated+types/* files

  • Avoid initial fetcher execution 404 error when Lazy Route Discovery is interrupted by a navigation (#​13564)

  • href replaces splats* (#​13593)

    consta=href("/products/*",{"*":"/1/edit"});// -> /products/1/edit

v7.6.0

Compare Source

Minor Changes
  • Added a newreact-router.config.tsrouteDiscovery option to configure Lazy Route Discovery behavior. (#​13451)

    • By default, Lazy Route Discovery is enabled and makes manifest requests to the/__manifest path:
      • routeDiscovery: { mode: "lazy", manifestPath: "/__manifest" }
    • 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" }
  • Add support for route component props increateRoutesStub. This allows you to unit test your route components using the props instead of the hooks: (#​13528)

    letRoutesStub=createRoutesStub([{path:"/",Component({ loaderData}){letdata=loaderDataas{message:string};return<predata-testid="data">Message:{data.message}</pre>;},loader(){return{message:"hello"};},},]);render(<RoutesStub/>);awaitwaitFor(()=>screen.findByText("Message: hello"));
Patch Changes
  • Fixreact-router module augmentation forNodeNext (#​13498)

  • Don't bundlereact-router inreact-router/dom CJS export (#​13497)

  • Fix bug where a submittingfetcher would get stuck in aloading state if a revalidatingloader redirected (#​12873)

  • Fix hydration error if a serverloader returnedundefined (#​13496)

  • Fix initial load 404 scenarios in data mode (#​13500)

  • StabilizeuseRevalidator'srevalidate function (#​13542)

  • Preserve status code if aclientAction throws adata() result in framework mode (#​13522)

  • Be defensive against leading double slashes in paths to avoidInvalid URL errors from the URL constructor (#​13510)

    • Note we do not sanitize/normalize these paths - we only detect them so we can avoid the error that would be thrown bynew URL("//", window.location.origin)
  • RemoveNavigator declaration fornavigator.connection.saveData to avoid messing with any other types beyondsaveData in userland (#​13512)

  • FixhandleErrorparams values on.data requests for routes with a dynamic param as the last URL segment (#​13481)

  • Don't trigger anErrorBoundary UI before the reload when we detect a manifest verison mismatch in Lazy Route Discovery (#​13480)

  • Inlineturbo-stream@2.4.1 dependency and fix decoding ordering of Map/Set instances (#​13518)

  • Only render dev warnings in DEV mode (#​13461)

  • UNSTABLE: Fix a few bugs with error bubbling in middleware use-cases (#​13538)

  • Short circuit post-processing on aborteddataStrategy requests (#​13521)

    • This resolves non-user-facing console errors of the formCannot read properties of undefined (reading 'result')

v7.5.3

Compare Source

Patch Changes
  • Fix bug where bubbled action errors would result inloaderData being cleared at the handlingErrorBoundary route (#​13476)
  • Handle redirects fromclientLoader.hydrate initial load executions (#​13477)

v7.5.2

Compare Source

Patch Changes
  • Update Single Fetch to also handle the 204 redirects used in?_data requests in Remix v2 (#​13364)

    • This allows applications to return a redirect on.data requests from outside the scope of React Router (i.e., anexpress/hono middleware)
    • ⚠️ Please note that doing so relies on implementation details that are subject to change without a SemVer major release
    • This is primarily done to ease upgrading to Single Fetch for existing Remix v2 applications, but the recommended way to handle this is redirecting from a route middleware
  • Adjust approach for Prerendering/SPA Mode via headers (#​13453)

v7.5.1

Compare Source

Patch Changes
  • Fix single fetch bug where no revalidation request would be made when navigating upwards to a reused parent route (#​13253)

  • When using the object-basedroute.lazy API, theHydrateFallback andhydrateFallbackElement properties are now skipped when lazy loading routes after hydration. (#​13376)

    If you move the code for these properties into a separate file, you can use this optimization to avoid downloading unused hydration code. For example:

    createBrowserRouter([{path:"/show/:showId",lazy:{loader:async()=>(awaitimport("./show.loader.js")).loader,Component:async()=>(awaitimport("./show.component.js")).Component,HydrateFallback:async()=>(awaitimport("./show.hydrate-fallback.js")).HydrateFallback,},},]);
  • Properly revalidate prerendered paths when param values change (#​13380)

  • UNSTABLE: Add a newunstable_runClientMiddleware argument todataStrategy to enable middleware execution in customdataStrategy implementations (#​13395)

  • UNSTABLE: Add better error messaging whengetLoadContext is not updated to return aMap" (#​13242)

  • Do not automatically addnull tostaticHandler.query()context.loaderData if routes do not have loaders (#​13223)

    • This was a Remix v2 implementation detail inadvertently left in for React Router v7
    • Now that we allow returningundefined from loaders, our prior check ofloaderData[routeId] !== undefined was no longer sufficient and was changed to arouteId in loaderData check - thesenull values can cause issues for this new check
    • ⚠️ This could be a "breaking bug fix" for you if you are doing manual SSR withcreateStaticHandler()/<StaticRouterProvider>, and usingcontext.loaderData to control<RouterProvider> hydration behavior on the client
  • Fix prerendering when a loader returns a redirect (#​13365)

  • UNSTABLE: Update context type forLoaderFunctionArgs/ActionFunctionArgs when middleware is enabled (#​13381)

  • Add support for the newunstable_shouldCallHandler/unstable_shouldRevalidateArgs APIs indataStrategy (#​13253)

v7.5.0

Compare Source

Minor Changes
  • Add granular object-based API forroute.lazy to support lazy loading of individual route properties, for example: (#​13294)

    createBrowserRouter([{path:"/show/:showId",lazy:{loader:async()=>(awaitimport("./show.loader.js")).loader,action:async()=>(awaitimport("./show.action.js")).action,Component:async()=>(awaitimport("./show.component.js")).Component,},},]);

    Breaking change forroute.unstable_lazyMiddleware consumers

    Theroute.unstable_lazyMiddleware property is no longer supported. If you want to lazily load middleware, you must use the new object-basedroute.lazy API withroute.lazy.unstable_middleware, for example:

    createBrowserRouter([{path:"/show/:showId",lazy:{unstable_middleware:async()=>(awaitimport("./show.middleware.js")).middleware,// etc.},},]);
Patch Changes
  • Introduceunstable_subResourceIntegrity future flag that enables generation of an importmap with integrity for the scripts that will be loaded by the browser. (#​13163)

v7.4.1

Compare Source

Patch Changes
  • Fix types onunstable_MiddlewareFunction to avoid type errors when a middleware doesn't return a value (#​13311)

  • Dedupe calls toroute.lazy functions (#​13260)

  • Add support forroute.unstable_lazyMiddleware function to allow lazy loading of middleware logic. (#​13210)

    Breaking change forunstable_middleware consumers

    Theroute.unstable_middleware property is no longer supported in the return value fromroute.lazy. If you want to lazily load middleware, you must useroute.unstable_lazyMiddleware.

v7.4.0

Compare Source

Patch Changes
  • Fix root loader data on initial load redirects in SPA mode (#​13222)
  • Load ancestor pathless/index routes in lazy route discovery for upwards non-eager-discoery routing (#​13203)
  • FixshouldRevalidate behavior forclientLoader-only routes inssr:true apps (#​13221)
  • UNSTABLE: FixRequestHandlerloadContext parameter type when middleware is enabled (#​13204)
  • UNSTABLE: UpdateRoute.unstable_MiddlewareFunction to have a return value ofResponse | undefined instead ofResponse | void becaue you should not return anything if you aren't returning theResponse (#​13199)
  • UNSTABLE(BREAKING): If a middleware throws an error, ensure we only bubble the error itself vianext() and are no longer leaking theMiddlewareError implementation detail (#​13180)

v7.3.0

Compare Source

Minor Changes
  • AddfetcherKey as a parameter topatchRoutesOnNavigation (#​13061)
    • In framework mode, Lazy Route Discovery will now detect manifest version mismatches after a new deploy
    • On navigations to undiscovered routes, this mismatch will trigger a document reload of the destination path
    • Onfetcher calls to undiscovered routes, this mismatch will trigger a document reload of the current path
Patch Changes
  • Skip resource route flow in dev server in SPA mode (#​13113)

  • Support middleware on routes (unstable) (#​12941)

    Middleware is implemented behind afuture.unstable_middleware flag. To enable, you must enable the flag and the types in yourreact-router-config.ts file:

    importtype{Config}from"@&#8203;react-router/dev/config";importtype{Future}from"react-router";declare module"react-router"{interfaceFuture{unstable_middleware:true;// 👈 Enable middleware types}}exportdefault{future:{unstable_middleware:true,// 👈 Enable middleware},}satisfiesConfig;

    ⚠️ Middleware is unstable and should not be adopted in production. There is at least one known de-optimization in route module loading forclientMiddleware that we will be addressing this before a stable release.

    ⚠️ Enabling middleware contains a breaking change to thecontext parameter passed to yourloader/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 asloader/action plus an additionalnext parameter to run the remaining data pipeline. This allows middlewares to perform logic before and after handlers execute.

    // Framework modeexportconstunstable_middleware=[serverLogger,serverAuth];// serverexportconstunstable_clientMiddleware=[clientLogger];// client// Library modeconstroutes=[{path:"/",// Middlewares are client-side for library mode SPA'sunstable_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:

    constclientLogger:Route.unstable_ClientMiddlewareFunction=async({ request},next,)=>{letstart=performance.now();// Run the remaining middlewares and all route loadersawaitnext();letduration=performance.now()-start;console.log(`Navigated to${request.url} (${duration}ms)`);};

    Note that in the above example, thenext/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 statefulrouter.

    For a server-side middleware, thenext function will return the HTTPResponse 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 bynext().

    constserverLogger:Route.unstable_MiddlewareFunction=async({ request, params, context},next,)=>{letstart=performance.now();// 👇 Grab the response hereletres=awaitnext();letduration=performance.now()-start;console.log(`Navigated to${request.url} (${duration}ms)`);// 👇 And return it here (optional if you don't modify the response)returnres;};

    You can throw aredirect from a middleware to short circuit any remaining processing:

    import{sessionContext}from"../context";constserverAuth:Route.unstable_MiddlewareFunction=({ request, params, context},next,)=>{letsession=context.get(sessionContext);letuser=session.get("user");if(!user){session.set("returnTo",request.url);throwredirect("/login",302);}};

    Note that in cases like this where you don't need to do any post-processing you don't need to call thenext function or return aResponse.

    Here's another example of using a server middleware to detect 404s and check the CMS for a redirect:

    constredirects:Route.unstable_MiddlewareFunction=async({  request,  next,})=>{// attempt to handle the requestletres=awaitnext();// if it's a 404, check the CMS for a redirect, do it last// because it's expensiveif(res.status===404){letcmsRedirect=awaitcheckCMSRedirects(request.url);if(cmsRedirect){throwredirect(cmsRedirect,302);}}returnres;};

    context parameter

    When middleware is enabled, your application will use a different type ofcontext parameter in your loaders and actions to provide better type safety. Instead ofAppLoadContext,context will now be an instance ofContextProvider that you can use with type-safe contexts (similar toReact.createContext):

    import{unstable_createContext}from"react-router";import{Route}from"./+types/root";importtype{Session}from"./sessions.server";import{getSession}from"./sessions.server";letsessionContext=unstable_createContext<Session>();constsessionMiddleware:Route.unstable_MiddlewareFunction=({  context,  request,})=>{letsession=awaitgetSession(request);context.set(sessionContext,session);//                          ^ must be of type Session};// ... then in some downstream middlewareconstloggerMiddleware:Route.unstable_MiddlewareFunction=({  context,  request,})=>{letsession=context.get(sessionContext);//  ^ typeof Sessionconsole.log(session.get("userId"),request.method,request.url);};// ... or some downstream loaderexportfunctionloader({ context}:Route.LoaderArgs){letsession=context.get(sessionContext);letprofile=awaitgetProfile(session.get("userId"));return{ profile};}

    If you are using a custom server with agetLoadContext function, the return value for initial context values passed from the server adapter layer is no longer an object and should now return anunstable_InitialContext (Map<RouterContext, unknown>):

    letadapterContext=unstable_createContext<MyAdapterContext>();functiongetLoadContext(req,res):unstable_InitialContext{letmap=newMap();map.set(adapterContext,getAdapterContext(req));returnmap;}
  • Fix types for loaderData and actionData that containedRecords (#​13139)

    UNSTABLE(BREAKING):

    unstable_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 optionalletx1=42asunknownasunstable_SerializesTo<number>;//          ^^^^^^^^^^// with the brand being marked as optionalletx2=42asunstable_SerializesTo<number>;

    However, this broke type inference inloaderData andactionData for anyRecord types as those would now (incorrectly) matchunstable_SerializesTo.
    This affected all users, not just those that depended onunstable_SerializesTo.
    To fix this, the branded property ofunstable_SerializesTo is marked as required instead of optional.

    For library and framework authors usingunstable_SerializesTo, you may need to addas unknown casts before casting tounstable_SerializesTo.

  • Fix single fetch_root.data requests when abasename is used (#​12898)

  • Addcontext support to client side data routers (unstable) (#​12941)

    Your applicationloader andaction functions on the client will now receive acontext parameter. This is an instance ofunstable_RouterContextProvider that you use with type-safe contexts (similar toReact.createContext) and is most useful with the correspondingmiddleware/clientMiddleware API's:

    import{unstable_createContext}from"react-router";typeUser={/*...*/};letuserContext=unstable_createContext<User>();functionsessionMiddleware({ context}){letuser=awaitgetUser();context.set(userContext,user);}// ... then in some downstream loaderfunctionloader({ context}){letuser=context.get(userContext);letprofile=awaitgetProfile(user.id);return{ profile};}

    Similar to server-side requests, a freshcontext will be created per navigation (orfetcher call). If you have initial data you'd like to populate in the context for every request, you can provide anunstable_getContext function at the root of your app:

    • Library mode -createBrowserRouter(routes, { unstable_getContext })
    • Framework mode -<HydratedRouter unstable_getContext>

    This function should return an value of typeunstable_InitialContext which is aMap<unstable_RouterContext, unknown> of context's and initial values:

    constloggerContext=unstable_createContext<(...args:unknown[])=>void>();functionlogger(...args:unknown[]){console.log(newDate.toISOString(), ...args);}functionunstable_getContext(){letmap=newMap();map.set(loggerContext,logger);returnmap;}

v7.2.0

Compare Source

Minor Changes
  • New type-safehref utility that guarantees links point to actual paths in your app (#​13012)

    import{href}from"react-router";exportdefaultfunctionComponent(){constlink=href("/blog/:slug",{slug:"my-first-post"}

Configuration

📅Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦Automerge: Disabled by config. Please merge this manually once you are satisfied.

Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕Ignore: Close this PR and you won't be reminded about these updates again.


  • If you want to rebase/retry this PR, check this box

This PR was generated byMend Renovate. View therepository job log.

@renovaterenovatebot requested a review fromnotrabNovember 22, 2024 08:51
@vercel
Copy link

vercelbot commentedNov 22, 2024
edited
Loading

The latest updates on your projects. Learn more aboutVercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
create-react-app-reduxErrorErrorNov 1, 2025 3:45pm

@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch fromc1520a4 tod3777a1CompareNovember 22, 2024 15:07
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch fromd3777a1 toe9d3916CompareDecember 3, 2024 03:37
@renovaterenovatebot changed the titlefix(deps): update react-router monorepo to v7 (major)fix(deps): update react-router monorepo to v7 (major) - autoclosedDec 8, 2024
@renovaterenovatebot closed thisDec 8, 2024
@renovaterenovatebot deleted the renovate/major-react-router-monorepo branchDecember 8, 2024 18:34
@renovaterenovatebot changed the titlefix(deps): update react-router monorepo to v7 (major) - autoclosedfix(deps): update react-router monorepo to v7 (major)Dec 9, 2024
@renovaterenovatebot reopened thisDec 9, 2024
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from9ac8e2d toe9d3916CompareDecember 9, 2024 06:41
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch frome9d3916 to9761826CompareDecember 20, 2024 21:03
@renovaterenovatebot changed the titlefix(deps): update react-router monorepo to v7 (major)fix(deps): update react-router monorepo to v6 (major)Dec 20, 2024
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from9761826 tof8453daCompareDecember 21, 2024 00:07
@renovaterenovatebot changed the titlefix(deps): update react-router monorepo to v6 (major)fix(deps): update react-router monorepo to v7 (major)Dec 21, 2024
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch fromf8453da to36c2479CompareDecember 23, 2024 20:43
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from36c2479 to2d52cdaCompareJanuary 16, 2025 17:41
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from2d52cda tod9630e9CompareJanuary 19, 2025 09:02
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch fromd9630e9 to45bacb9CompareJanuary 30, 2025 17:13
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from45bacb9 to101fa75CompareFebruary 1, 2025 20:56
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from101fa75 to2bb750eCompareFebruary 18, 2025 21:52
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from551f08b to43fa4f4CompareMay 8, 2025 15:54
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from43fa4f4 to3df2c73CompareMay 25, 2025 14:01
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from3df2c73 tode72e81CompareJune 5, 2025 21:28
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch fromde72e81 to3514daaCompareJune 27, 2025 19:14
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from3514daa tofcddf44CompareJuly 17, 2025 00:00
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch fromfcddf44 to4912012CompareJuly 25, 2025 00:55
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from4912012 to76e166eCompareAugust 7, 2025 21:29
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from76e166e toe1010fbCompareAugust 15, 2025 21:29
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch frome1010fb toc7cb9bfCompareAugust 22, 2025 23:02
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch fromc7cb9bf to8276468CompareSeptember 13, 2025 20:02
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from8276468 to7ba9b12CompareSeptember 24, 2025 18:08
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch from7ba9b12 tobd0900eCompareSeptember 26, 2025 20:32
@renovaterenovatebotforce-pushed therenovate/major-react-router-monorepo branch frombd0900e tocebb7d1CompareOctober 8, 2025 19:12
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

@notrabnotrabAwaiting requested review from notrab

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

1 participant


[8]ページ先頭

©2009-2025 Movatter.jp