Skip to Content
NewNext-TS-API 1.0 is releasedGet started →
DocsExamples

Examples

This page provides practical examples of using Next-TS-API in common scenarios.

Basic CRUD Operations

Todo List API

A complete example of a Todo List API with type-safe endpoints:

// app/api/todos/route.ts import { NextApiRequest } from 'next-ts-api'; import { NextResponse } from 'next/server'; interface Todo { id: string; title: string; completed: boolean; } const todos: Todo[] = []; // GET /api/todos export async function GET( request: NextApiRequest<null, { completed?: string; }> ) { const searchParams = request.nextUrl.searchParams; const completed = searchParams.get('completed'); return NextResponse.json( todos.filter(todo => todo.completed === (completed === 'true')) ); } // POST /api/todos export async function POST( request: NextApiRequest<{ title: string; }> ) { const { title } = await request.json(); const newTodo: Todo = { id: Math.random().toString(), title, completed: false }; return NextResponse.json(newTodo); } // PUT /api/todos export async function PUT( request: NextApiRequest<{ id: string; title?: string; completed?: boolean; }> ) { const updates = await request.json(); // Example response - in real app, update in database return NextResponse.json({ id: updates.id, title: updates.title, completed: updates.completed }); } // DELETE /api/todos/[id] export async function DELETE( request: NextApiRequest, { params }: { params: { id: string } } ) { const { id } = params; // Example response - in real app, delete from database return NextResponse.json({ success: true, deletedId: id }); }

Using the API Client

// lib/api.ts import { createNextFetchApi } from "next-ts-api"; import { type ApiRoutes } from "../types/next-ts-api"; export const api = createNextFetchApi<ApiRoutes>();
// app/todos/page.tsx 'use client'; import { api } from '@/lib/api'; import { useState, useEffect } from 'react'; interface Todo { id: string; title: string; completed: boolean; } export default function TodosPage() { const [todos, setTodos] = useState<Todo[]>([]); // Fetch completed todos const fetchTodos = async () => { const response = await api('todos', { method: 'GET', query: { completed: 'true' } }); const data = await response.json(); setTodos(data); }; // Create a new todo const createTodo = async (title: string) => { const response = await api('todos', { method: 'POST', body: { title } }); const newTodo = await response.json(); setTodos([...todos, newTodo]); }; // Update a todo const updateTodo = async (todo: Todo) => { const response = await api('todos', { method: 'PUT', body: todo }); const updatedTodo = await response.json(); setTodos(todos.map(t => t.id === updatedTodo.id ? updatedTodo : t)); }; // Delete a todo const deleteTodo = async (id: string) => { await api(`todos/[id]`, { method: 'DELETE', params: { id } }); setTodos(todos.filter(t => t.id !== id)); }; return ( <div> {/* Your JSX implementation here */} </div> ); }

File Uploads

Send files and fields as multipart form data with full type safety.

// app/api/upload/route.ts import { NextApiRequest } from 'next-ts-api'; import { NextResponse } from 'next/server'; export async function POST( request: NextApiRequest<{ file: File; name: string }> ) { const data = await request.formData(); const file = data.get('file'); const name = data.get('name'); if (!(file instanceof File)) { return NextResponse.json({ error: 'file required' }, { status: 400 }); } // ...store the file, then return its URL return NextResponse.json({ url: '/uploads/' + file.name, name }); }
// app/upload/page.tsx 'use client'; import { api } from '@/lib/api'; export default function UploadForm() { const handleUpload = async (file: File) => { const response = await api('upload', { method: 'POST', form: { file, name: file.name, // Type checked against the handler! }, }); const { url } = await response.json(); console.log('Uploaded to', url); }; return ( <input type="file" onChange={(e) => { const file = e.target.files?.[0]; if (file) handleUpload(file); }} /> ); }

Dynamic Route Params

Path segments like [id] are filled with the typed params option:

// GET /api/todo/[id] const response = await api('todo/[id]', { method: 'GET', params: { id: 'abc-123' }, // Type checked! }); const todo = await response.json();

Next Steps

Last updated on