Type API boundaries in TypeScript: generate types from OpenAPI, validate responses at runtime with Zod 4, type pagination and query params, and test types against real payloads.
.cursor/rules/typescript-api-types.mdc. Downloaded files need to be placed in that repository path.---
description: "Type API boundaries in TypeScript: generate types from OpenAPI, validate responses at runtime with Zod 4, type pagination and query params, and test types against real payloads."
globs: "**/*"
alwaysApply: false
---
Apply these rules to code that calls or implements HTTP APIs in TypeScript.
## Where types come from
- If the API has an OpenAPI document, generate types (for example with `openapi-typescript`) and regenerate them in CI when the spec changes. Do not hand-edit generated files.
- Without a spec, define a runtime schema per endpoint and derive the TypeScript type from it, so the type and the validation cannot drift apart.
## Runtime validation
- TypeScript types disappear at run time. Validate untrusted data at the boundary: request bodies on the server, and responses from third-party or external APIs on the client.
```ts
import { z } from 'zod';
export const UserSchema = z.object({
id: z.string(),
email: z.email(),
name: z.string().nullable(),
createdAt: z.iso.datetime(),
});
export type User = z.infer<typeof UserSchema>;
export const PageSchema = <T extends z.ZodType>(item: T) =>
z.object({ items: z.array(item), nextCursor: z.string().nullable() });
export const UserPageSchema = PageSchema(UserSchema);
export type UserPage = z.infer<typeof UserPageSchema>;
export async function getUsers(cursor?: string): Promise<UserPage> {
const url = new URL('/api/users', location.origin);
if (cursor) url.searchParams.set('cursor', cursor);
const res = await fetch(url);
if (!res.ok) throw new Error(`GET /api/users failed: ${res.status}`);
const parsed = UserPageSchema.safeParse(await res.json());
if (!parsed.success) throw new Error(`Unexpected /api/users payload: ${z.prettifyError(parsed.error)}`);
return parsed.data;
}
```
- In Zod 4, use top-level string formats (`z.email()`, `z.url()`, `z.iso.datetime()`); the `z.string().email()` forms are deprecated. Read validation problems from `error.issues` (`error.errors` was removed).
## Shapes
- Pair request and response types per endpoint (`CreateUserRequest` / `CreateUserResponse`), and keep one generic pagination shape across the API (cursor or offset, not both).
- Type query parameters as an object (`{ page?: number; sort?: 'name' | 'createdAt' }`) and serialize them in one helper, converting numbers and Booleans explicitly.
- Represent dates as ISO strings in transport types; convert to `Date` in a mapping layer if needed.
## Clients
- Expose a small typed client (one function per endpoint, or a generated client) instead of calling `fetch` with string URLs across the codebase. Handle non-2xx responses explicitly.
## Versioning
- When the API is versioned, keep types per version (`v1/`, `v2/`) or regenerate from each version's spec, and remove old types when the version is retired.
## Testing types against reality
- Validate recorded or sandbox responses against the schemas in tests, and log or report schema failures in production instead of silently casting with `as`.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A dashboard casts fetch results with `as User[]`; a backend change renamed created_at and the UI shows 'Invalid Date' without any error.
Apply the TypeScript API Types rule to src/api/users.ts. No OpenAPI spec exists; the backend returns { items, nextCursor }. Zod 4 is installed.A UserSchema and generic page schema with z.infer types, a getUsers(cursor?) function that checks res.ok, validates with safeParse and reports z.prettifyError output, no `as` casts on response data, and a test that validates a recorded response fixture.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/typescript-api-types.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "TypeScript API Types project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules to code that calls or implements HTTP APIs in TypeScript.
## Where types come from
- If the API has an OpenAPI document, generate types (for example with `openapi-typescript`) and regenerate them in CI when the spec changes. Do not hand-edit generated files.
- Without a spec, define a runtime schema per endpoint and derive the TypeScript type from it, so the type and the validation cannot drift apart.
## Runtime validation
- TypeScript types disappear at run time. Validate untrusted data at the boundary: request bodies on the server, and responses from third-party or external APIs on the client.
```ts
import { z } from 'zod';
export const UserSchema = z.object({
id: z.string(),
email: z.email(),
name: z.string().nullable(),
createdAt: z.iso.datetime(),
});
export type User = z.infer<typeof UserSchema>;
export const PageSchema = <T extends z.ZodType>(item: T) =>
z.object({ items: z.array(item), nextCursor: z.string().nullable() });
export const UserPageSchema = PageSchema(UserSchema);
export type UserPage = z.infer<typeof UserPageSchema>;
export async function getUsers(cursor?: string): Promise<UserPage> {
const url = new URL('/api/users', location.origin);
if (cursor) url.searchParams.set('cursor', cursor);
const res = await fetch(url);
if (!res.ok) throw new Error(`GET /api/users failed: ${res.status}`);
const parsed = UserPageSchema.safeParse(await res.json());
if (!parsed.success) throw new Error(`Unexpected /api/users payload: ${z.prettifyError(parsed.error)}`);
return parsed.data;
}
```
- In Zod 4, use top-level string formats (`z.email()`, `z.url()`, `z.iso.datetime()`); the `z.string().email()` forms are deprecated. Read validation problems from `error.issues` (`error.errors` was removed).
## Shapes
- Pair request and response types per endpoint (`CreateUserRequest` / `CreateUserResponse`), and keep one generic pagination shape across the API (cursor or offset, not both).
- Type query parameters as an object (`{ page?: number; sort?: 'name' | 'createdAt' }`) and serialize them in one helper, converting numbers and Booleans explicitly.
- Represent dates as ISO strings in transport types; convert to `Date` in a mapping layer if needed.
## Clients
- Expose a small typed client (one function per endpoint, or a generated client) instead of calling `fetch` with string URLs across the codebase. Handle non-2xx responses explicitly.
## Versioning
- When the API is versioned, keep types per version (`v1/`, `v2/`) or regenerate from each version's spec, and remove old types when the version is retired.
## Testing types against reality
- Validate recorded or sandbox responses against the schemas in tests, and log or report schema failures in production instead of silently casting with `as`.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.