Back to listTypeScript
Next.js API Route Handler
Lv.5750@mukitaro10 playsDec 28, 2025
Next.js API route with TypeScript types. Vercel's React framework.
preview.ts
1import type { NextApiRequest, NextApiResponse } from 'next';2 3type User = {4 id: number;5 name: string;6 email: string;7};8 9type ErrorResponse = {10 error: string;11};12 13export default async function handler(14 req: NextApiRequest,15 res: NextApiResponse<User | User[] | ErrorResponse>16) {17 if (req.method === 'GET') {18 const users: User[] = [19 { id: 1, name: 'Alice', email: 'alice@example.com' },20 { id: 2, name: 'Bob', email: 'bob@example.com' }21 ];22 return res.status(200).json(users);23 }24 25 if (req.method === 'POST') {26 const { name, email } = req.body;27 const user: User = { id: Date.now(), name, email };28 return res.status(201).json(user);29 }30 31 return res.status(405).json({ error: 'Method not allowed' });32}Custom problems are not included in rankings