Typing API Routes with TypeScript
When typing API Routes with TypeScript in Next.js, you can ensure type safety by defining types for request and response objects as well as for response data. Here’s how you can do it:
1. Typing Request and Response Objects:
In your API route files (`pages/api/…`), import the appropriate types from `next` to type the request and response objects.
For example, to type a GET request and response:
```typescript
// pages/api/users.ts
import { NextApiRequest, NextApiResponse } from 'next';
type Data = {
id: number;
name: string;
email: string;
};
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const userData: Data = { id: 1, name: 'John Doe', email: 'john@example.com' };
res.status(200).json(userData);
}
```
In this example, `NextApiRequest` and `NextApiResponse<Data>` are imported from `next` and used to type the request and response objects, respectively. The `Data` type represents the structure of the response data.
2. Typing Response Data:
Define types for the data you expect to send in the response. This can be done using TypeScript interfaces or types.
For example, defining an interface for user data:
```typescript
// types/User.ts
export interface User {
id: number;
name: string;
email: string;
}
```
Then, use this interface in your API route to type the response data:
```typescript
// pages/api/users.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { User } from '../../types/User';
export default function handler(
req: NextApiRequest,
res: NextApiResponse<User>
) {
const userData: User = { id: 1, name: 'John Doe', email: 'john@example.com' };
res.status(200).json(userData);
}
```
Here, `User` is imported from the `User.ts` file in the `types` directory to type the response data.
How to use Next.js API Routes?
Next.js API Routes are a feature of Next.js that allows you to create server-side logic and APIs within your Next.js application. These API routes are implemented using files in the `pages/api` directory of your Next.js project. When you deploy your Next.js application, these API routes are automatically served as serverless functions.
Table of Content
- Key points about Next.js API Routes
- Dynamic API Routes
- Creating an API Route
- API Routes custom configuration
- Typing API Routes with TypeScript
- Accessing an API Route
- Conclusion