API Reference
This page provides detailed documentation for Next-TS-API’s core APIs and types.
Core Types
NextApiRequest
type NextApiRequest<Body, Query = Record<string, string>> = {
json: () => Promise<Body>;
nextUrl: {
searchParams: URLSearchParamsType<Query>;
}
}
The NextApiRequest
type extends the standard Next.js Request
type with type-safe body parsing.
ApiRoutes
type ApiRoutes = {
[path: string]: {
[method in HttpMethod]?: {
body?: unknown;
response: unknown;
params?: Record<string, string>;
query?: Record<string, string>;
};
};
};
Generated type that describes your API routes structure.
HttpMethod
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
Supported HTTP methods.
API Client
createNextFetchApi
function createNextFetchApi<T extends ApiRoutes>(config?: {
baseUrl?: string;
}): ApiClient<T>;
Creates a type-safe API client for your routes.
ApiClient
type ApiClient<T extends ApiRoutes> = <
TPath extends keyof T,
TMethod extends keyof T[TPath]
>(
path: TPath,
options: {
method: TMethod;
body?: T[TPath][TMethod]['body'];
params?: T[TPath][TMethod]['params'];
query?: T[TPath][TMethod]['query'];
headers?: HeadersInit;
}
) => Promise<T[TPath][TMethod]['response']>;
The type-safe API client function type.
Configuration
nextTsApi
import { nextTsApi } from 'next-ts-api/config';
function nextTsApi(options?: {
dir?: string;
outDir?: string;
outFile?: string;
}): Plugin;
Next.js plugin for type generation.
Parameters:
options.dir
: The directory to scan for API routesoptions.outDir
: The directory to output the generated typesoptions.outFile
: The file to output the generated types
Example:
// next.config.js
const { nextTsApi } = require('next-ts-api/config');
const withNextTsApi = nextTsApi({
outDir: 'src/types',
});
const nextConfig = {
// ... your other config
};
export default withNextTsApi(nextConfig);
Custom error class for API errors.
Next Steps
- See Examples for practical usage
- Learn about Core Concepts
- Check out Contributing guidelines
Last updated on