πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

API Security

Next.js Security🟒 Free Lesson

Advertisement

API Security

Authentication, authorization, rate limiting, input validation, and CORS.

Overview

Secure APIs protect against common attacks and unauthorized access.

Key Concepts

  • Authentication β€” Verify user identity
  • Authorization β€” Control resource access
  • Rate Limiting β€” Prevent abuse
  • Input Validation β€” Sanitize all inputs
  • CORS β€” Control cross-origin requests

Code Examples

// app/api/auth/route.js
import { NextResponse } from 'next/server';
import { verifyToken } from '@/lib/auth';

export async function middleware(request) {
  const token = request.headers.get('authorization')?.replace('Bearer ', '');

  if (!token) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const payload = await verifyToken(token);
    request.headers.set('x-user-id', payload.sub);
    return NextResponse.next();
  } catch {
    return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
  }
}

// Rate limiting
const rateLimit = new Map();

export function checkRateLimit(ip, limit = 100, windowMs = 60000) {
  const now = Date.now();
  const requests = rateLimit.get(ip) || [];
  const recentRequests = requests.filter(time => now - time < windowMs);
  
  if (recentRequests.length >= limit) {
    return false;
  }
  
  recentRequests.push(now);
  rateLimit.set(ip, recentRequests);
  return true;
}

// Input validation with Zod
import { z } from 'zod';

const createPostSchema = z.object({
  title: z.string().min(1).max(200),
  content: z.string().min(1).max(5000),
  tags: z.array(z.string()).max(5).optional()
});

export async function POST(request) {
  const body = await request.json();
  
  const result = createPostSchema.safeParse(body);
  if (!result.success) {
    return NextResponse.json(
      { errors: result.error.flatten().fieldErrors },
      { status: 400 }
    );
  }

  // Safe to use result.data
  const post = await db.posts.create({ data: result.data });
  return NextResponse.json({ data: post }, { status: 201 });
}

Practice

Implement comprehensive API security with auth, rate limiting, and validation.

⭐

Premium Content

API Security

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement