Créer une route API Next.js

VérifiéSûr

Crée une nouvelle route API Next.js App Router avec validation Zod, gestion d'erreurs, et options de limitation de débit et d'authentification. Accélère la mise en place de routes robustes et sécurisées.

Spar Skills Guide Bot
DeveloppementIntermédiaire
5002/06/2026
Claude CodeCursorWindsurf
#nextjs#api-route#zod#typescript#error-handling

Recommandé pour

Notre avis

Génère une nouvelle route API Next.js dans l'App Router avec des types TypeScript, une validation Zod, une gestion d'erreurs, et optionnellement du rate limiting ou de l'authentification.

Points forts

  • Fournit un modèle standardisé avec une gestion d'erreurs et une validation appropriées.
  • Supporte l'intégration avec Arcjet pour la limitation de débit et Clerk pour l'authentification.
  • Génère du code TypeScript propre avec validation typée des requêtes.
  • Réduit le code répétitif et assure une structure cohérente des routes API.

Limites

  • Ne supporte que l'App Router de Next.js, pas le Pages Router.
  • Suppose que les bibliothèques spécifiques (Zod, Arcjet, Clerk) sont déjà configurées dans le projet.
  • Ne couvre pas les scénarios avancés comme les téléchargements de fichiers ou les réponses en streaming.
Quand l'utiliser

Lorsque vous avez besoin de structurer rapidement un nouveau point de terminaison API dans un projet Next.js App Router avec validation et bonnes pratiques de sécurité.

Quand l'éviter

Lors de la création de routes dans le Pages Router, ou si vous préférez une autre bibliothèque de validation ou fournisseur d'authentification.

Analyse de sécurité

Sûr
Score qualité85/100

The skill provides a template for creating Next.js API routes with best practices like input validation, error handling, and optional rate limiting/authentication. It does not include any destructive, exfiltrating, or obfuscated instructions, and uses standard development patterns.

Aucun point d'attention détecté

Exemples

Create public API route with rate limiting
Add a new public API route called 'feedback' that accepts POST requests. Include Zod validation for an email and message field, and add Arcjet rate limiting.
Create protected API route with authentication
Create a protected API route for 'profile/update' that uses Clerk for authentication. It should accept a PUT method and validate a name field using Zod.

Add API Route

Create a new Next.js API route with proper patterns.

Description

Creates a new API route in the Next.js App Router with:

  • TypeScript types
  • Zod input validation
  • Error handling
  • Rate limiting setup (optional)
  • Authentication check (optional)

Instructions

  1. Create a new folder in app/api/[route-name]/
  2. Create route.ts with the appropriate HTTP handlers
  3. Add Zod schema for request validation
  4. Include proper error handling with status codes
  5. Add rate limiting using Arcjet if public-facing
  6. Add Clerk authentication if the endpoint is protected

Parameters

  • route_name - The URL path for the route (e.g., "webhooks", "notifications")
  • methods - HTTP methods to support (GET, POST, PUT, DELETE)
  • is_public - Whether the route is public or requires auth
  • needs_rate_limit - Whether to add Arcjet rate limiting

Template

import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';

// Input validation schema
const RequestSchema = z.object({
  // Define your schema here
});

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const validated = RequestSchema.parse(body);
    
    // Your logic here
    
    return NextResponse.json({ success: true });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: 'Validation failed', details: error.errors },
        { status: 400 }
      );
    }
    
    console.error('API Error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

Examples

Public endpoint with rate limiting

import { arcjet } from '@/lib/arcjet';

export async function POST(request: NextRequest) {
  const decision = await arcjet.protect(request);
  if (decision.isDenied()) {
    return NextResponse.json({ error: 'Rate limited' }, { status: 429 });
  }
  // ... rest of handler
}

Protected endpoint

import { auth } from '@clerk/nextjs/server';

export async function POST(request: NextRequest) {
  const { userId } = await auth();
  if (!userId) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
  // ... rest of handler
}
Skills similaires