CodShot
TypeScript Public

Next.js Route Handler with JSON Validation

Validate a JSON request body and return typed responses from an App Router Route Handler.

#nextjs #route-handler #api #typescript
TypeScript
// app/api/tasks/route.ts

import { NextResponse } from 'next/server';

type CreateTaskBody = {
  title?: unknown;
};

export async function POST(request: Request) {
  let body: CreateTaskBody;

  try {
    body = await request.json();
  } catch {
    return NextResponse.json(
      { error: 'Invalid JSON body.' },
      { status: 400 },
    );
  }

  const title = String(body.title ?? '').trim();

  if (title.length < 3) {
    return NextResponse.json(
      { error: 'Title must contain at least 3 characters.' },
      { status: 422 },
    );
  }

  const task = await db.task.create({
    data: { title },
  });

  return NextResponse.json(
    { data: task },
    { status: 201 },
  );
}

Snippet actions

CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0
Forks
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support