Skip to content
This repository was archived by the owner on Oct 26, 2026. It is now read-only.

Commit 8f4cfe6

Browse files
ToTeToGabrola
andauthored
fix(core): validate response (#538)
Co-authored-by: Youssef Gaber <1728215+Gabrola@users.noreply.github.com>
1 parent 6577bd3 commit 8f4cfe6

4 files changed

Lines changed: 81 additions & 11 deletions

File tree

‎.changeset/beige-forks-sit.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@ts-rest/core': patch
3+
---
4+
5+
Fix client not validating response

‎apps/docs/docs/core/fetch.md‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,51 @@ This will ensure that you could pass Date objects in your client queries. They w
145145

146146
:::
147147

148+
## Validate Response
149+
150+
The `validateResponse` option allows you to validate the response body against the response schema. This is useful for ensuring that the server is returning the correct response type or performing transformations that are part of the response schema. For this to work, the responses schema must be defined using Zod (`c.type<>` will not check types at runtime).
151+
152+
```typescript
153+
const c = initContract();
154+
export const contract = c.router({
155+
method: 'GET',
156+
path: '/post/:id',
157+
responses: {
158+
200: z.object({
159+
id: z.string(),
160+
createdAt: z.coerce.date(),
161+
}),
162+
},
163+
});
164+
165+
const client = initClient(contract, { validateResponse: true });
166+
const response = await client.getPost({ id: '1' });
167+
// response will be validated against the response schema
168+
if (response.status === 200) {
169+
// response.data will be of type { id: string, createdAt: Date }
170+
// because `createdAt` has transformation of `z.coerce.date()`, it will parse any string date into a Date object
171+
}
172+
```
173+
174+
:::caution
175+
176+
If you are doing any non-idempotent Zod transforms that run on the server, response validation may fail on the client or produce an unintended double transformation is certain cases. Make sure your transformations are idempotent.
177+
178+
```typescript
179+
// ❌❌
180+
z.date().transform((d) => d.toISOString());
181+
z.number().transform((n) => n + 1000);
182+
z.string().transform((s) => `Hello, ${s}`);
183+
184+
// ✅✅
185+
z.coerce.date();
186+
z.string().transform((s) => s.toUpperCase());
187+
z.union([z.string().datetime(), z.date()])
188+
.transform((date) => (typeof date === 'string' ? new Date(date) : date));
189+
```
190+
191+
:::
192+
148193
## Notes About Basic Fetch Client
149194

150195
We use the [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) API under the hood.

‎libs/ts-rest/core/src/lib/client.spec.ts‎

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,19 @@ import {
77
} from '..';
88
import { ApiFetcherArgs, initClient } from './client';
99
import { Equal, Expect } from './test-helpers';
10-
import { z } from 'zod';
10+
import { z, ZodError } from 'zod';
1111

1212
const c = initContract();
1313

14-
export type Post = {
15-
id: string;
16-
title: string;
17-
description: string | null;
18-
content: string | null;
19-
published: boolean;
20-
authorId: string;
21-
};
14+
const postSchema = z.object({
15+
id: z.string(),
16+
title: z.string(),
17+
description: z.string().nullable(),
18+
content: z.string().nullable(),
19+
published: z.boolean(),
20+
authorId: z.string(),
21+
});
22+
export type Post = z.infer<typeof postSchema>;
2223

2324
export type User = {
2425
id: string;
@@ -34,7 +35,7 @@ const postsRouter = c.router({
3435
'x-api-key': z.string().optional(),
3536
}),
3637
responses: {
37-
200: c.type<Post | null>(),
38+
200: postSchema.nullable(),
3839
},
3940
},
4041
getPosts: {
@@ -141,7 +142,7 @@ export const router = c.router(
141142
upload: {
142143
method: 'POST',
143144
path: '/upload',
144-
body: c.body<{ file: File }>(),
145+
body: c.type<{ file: File }>(),
145146
responses: {
146147
200: c.type<{ message: string }>(),
147148
},
@@ -954,4 +955,22 @@ describe('custom api', () => {
954955
'Server returned unexpected response. Expected one of: 200 got: 419',
955956
);
956957
});
958+
959+
it('throw an error when validateResponse is configured and response is invalid', async () => {
960+
const client = initClient(router, {
961+
baseUrl: 'https://isolated.com',
962+
baseHeaders: {
963+
'X-Api-Key': 'foo',
964+
},
965+
validateResponse: true,
966+
});
967+
fetchMock.getOnce(
968+
{ url: 'https://isolated.com/posts/1' },
969+
{ status: 200, body: { key: 'invalid value' } },
970+
);
971+
972+
await expect(
973+
client.posts.getPost({ params: { id: '1' } }),
974+
).rejects.toThrowError(ZodError);
975+
});
957976
});

‎libs/ts-rest/core/src/lib/client.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@ export const fetchApi = ({
215215
rawBody: body,
216216
rawQuery: query,
217217
contentType: undefined,
218+
validateResponse: clientArgs.validateResponse,
218219
fetchOptions: {
219220
...(clientArgs.credentials && { credentials: clientArgs.credentials }),
220221
...fetchOptions,

0 commit comments

Comments
 (0)