Migrating to 2.0
This page lists what changed between 1.x and 2.0 of @navios/builder and @navios/react-query, as before and after, and what changed in @navios/http. Upgrade the packages together: @navios/react-query 2.0 is built on @navios/builder 2.0 and requires @tanstack/react-query ^5.102.0.
The short version: there is one way to declare an endpoint, two ways to call it, and one error type. Most of the work is deleting code.
@navios/builder
One declareEndpoint
Uploads and downloads are options of declareEndpoint, not separate methods.
response also accepts 'text', 'stream' and 'void'. See File uploads and Downloads and streams.
The input is sent, not the output
1.x validated the arguments of a call and sent what the schemas made of them. 2.0 validates them and sends what you passed, because the server that parses the request with the same schemas would otherwise apply every transform twice.
Before the request leaves, your schemas no longer
- fill in defaults. A field you leave out is not sent. Only a URL parameter you leave out is still sent as the default of
urlParamsSchema. - remove unknown keys. An object with more keys than its schema is sent with all of them.
- run transforms,
trim(), coercion and the like. The value goes out as you passed it.
A Navios server does all of this when it parses the request, so a shared contract needs no change. Code that calls another API and relies on one of the three does: check every .default(), .transform() and z.coerce in a requestSchema, querySchema or urlParamsSchema, and every call that passes an object with more keys than the API accepts. To keep the behavior of 1.x for such an API:
What is sent describes both modes. Responses are unchanged: you receive the output of responseSchema.
Errors are EndpointError
Every failed call now produces an EndpointError. HTTP errors are no longer the HTTP client's own error, and invalid input is no longer a raw ZodError. errorSchema applies to every call, and the parsed body is exactly the schema's output: the __status field is gone.
If you used useDiscriminatorResponse to receive errors as values, call .safe() instead:
If you caught exceptions, check for EndpointError first:
For a Zod schema the original ZodError is still available on error.cause. Errors describes every kind.
One onError hook
onZodError is removed, and onError receives the EndpointError instead of unknown. It is called once per failed call with the same instance the caller gets.
Headers and timeout are endpoint options
clientOptions now carries client-specific keys only, such as withCredentials, and cannot override what the builder sets. clientOptions.timeout is ignored, and transformRequest / transformResponse are gone. clientOptions.headers are still sent, underneath the endpoint's headers.
Passing the client
provideClient still works at start-up. For a per-request client, pass it to the call instead of swapping the shared one:
Behavior to re-check
- Non-2xx is always an error. Builder checks the status itself, whether the client resolved or rejected. A client configured to resolve on 4xx no longer turns those into successful results.
- Unknown endpoint options are compile errors. Typos and removed options such as
resultare reported by the compiler. urlParamsSchemakeys must equal the URL's parameter names. A mismatch throws when the endpoint is declared. The check runs for schemas that expose their keys as.shape, as a Zod object does.- Contradicting options are errors, for the compiler and when the endpoint is declared:
responseswithresponseSchema, a response schema with a non-JSONresponse, and a body onGETorHEAD. - URL parameter names are a letter or underscore followed by letters, digits or underscores, so
/files/$id.jsonhas the parameterid. An empty string counts as a missing parameter..,.., objects, arrays andNaNare refused, and aDateis written as an ISO string. - Primitive JSON bodies are encoded: a string body of
requestSchema: z.string()is sent as a JSON string, not as it is, and0,falseandnullare sent. A body the client cannot serialise, such as aBigIntin JSON, fails with kindconfig. - Header names are merged without regard to case across
clientOptions.headers, the endpoint'sheadersand those of the call. safe()never rejects, also not for a client that resolves with nothing or for headers thatHeadersrefuses.dataandparamsare optional when their schema accepts an empty object orundefined, andendpoint()takes no argument when nothing is required.validateResponse: falsetypes the result as the schema's input, because transforms and defaults are not applied.- Multipart bodies:
Blobvalues are sent as binary parts, aFormDatainstance is sent as it is, andundefinedfields are left out. - Schemas are Standard Schema. Every slot accepts any Standard Schema library, and
zodis no longer a peer dependency.error.issuesare plain objects,{ message, path?, part? }, without the validated value and without fields specific to a library. Those are onerror.cause.
Removed and renamed exports
The Zod-narrowed option types ZodBaseEndpointOptions, ZodEndpointOptions and ZodSchemaSlots are removed and no package exports them.
The current names are listed in the @navios/builder API.
Socket and EventSource
Both builders have a single onError hook that receives a typed error. The separate callbacks are removed.
Send functions throw and reject with a SocketError instead of a ZodError or a plain Error:
What else changed:
- Socket.IO is not supported. A stock Socket.IO client never understood the frames of
socketBuilder. UsedeclareWebSocket, or a client of your own with the same methods. - A frame that cannot be sent is an error.
emit,sendRawand send functions fail with kindtransportwhen the socket is not open, where 1.x reported the failure toonErrorat most. Pending acknowledgements are rejected when the connection closes.emittakes no callback; useackSchema. - A send with an
ackSchemaalways rejects, also for an invalid payload. It never throws. eventSourceBuilder.provideClientno longer closes the previous connection. Pass{ closePrevious: true }. Both builders ignore the client they already have, and both accept subscriptions before there is one.on('open')andon('error')of anEventSourcehandle listen to server events of these names. UseonOpenandonErrorfor the connection.querySchemais applied whenparamsis left out, so its defaults are sent and its required fields are required. A handler is called without arguments when nothing is required.- Payloads of events are validated as decoded from JSON. A number, a boolean or
nullthat fails is tried as the text that arrived. issuesof both errors are plain objects,{ message, path? }.
createWebSocketHandler({ onError }) and createEventSourceHandler({ onError }) also receive the typed error, with the thrown value on cause. See WebSocket and Server-Sent Events.
@navios/http
Mocks of @navios/http/testing may be asynchronous and match a query; requests records what was sent, and reset() forgets both. HTTP client describes the client.
@navios/react-query
Three client methods
declareClient returns { query, infiniteQuery, mutation }. Each accepts an inline declaration or an existing endpoint, so the FromEndpoint variants and multipartMutation are gone.
Errors live in the error channel
Errors are never returned as data. Queries and mutations call the throwing form of the endpoint, so error, onError and error boundaries receive the typed EndpointError.
onFail is removed from every helper. Use the builder's onError, or the mutation's.
processResponse becomes select
Hooks accept every TanStack option except queryKey and queryFn. For mutations, transform the result in onSuccess or at the call site.
Keys and invalidation
query.key(args?) replaces queryKey and its members, and invalidate covers what invalidateAll did.
Every cache key changed shape. Discard caches persisted by 1.x, for example by changing the persister's buster.
The new shape is described in Keys and invalidation.
Mutations
Mutation hooks take no arguments, every mutation has a mutationKey, and URL params always go to mutate. useKey is removed.
Callbacks receive one merged context as their last argument. It already contains the QueryClient as context.client, and the value returned from onMutate as context.onMutateResult. Invalidation after success has its own setting.
Optimistic updates
Return an array of update(...) calls where you used createMultiOptimisticUpdate.
Prefetching
The helpers are methods of the query object.
Infinite queries
The page param is an object of query params, merged over the call's params. initialPageParam is optional and defaults to those params.
Removed exports
The current names are listed in the @navios/react-query API.