GuardAPI Logo
GuardAPI

Fix BOLA (Broken Object Level Authorization) in Next.js

BOLA (Broken Object Level Authorization), or IDOR, is the most exploited vulnerability in modern web apps. In Next.js, it occurs when API routes or Server Actions accept a resource ID from the client and fetch the data without verifying if the authenticated user actually owns that resource. If an attacker can change `?id=123` to `?id=124` and see another user's data, your authorization logic is broken.

The Vulnerable Pattern

export default async function handler(req, res) {
  const { id } = req.query;

// VULNERABLE: The ‘id’ is taken directly from the URL. // An attacker can enumerate IDs to scrape the entire database. const invoice = await prisma.invoice.findUnique({ where: { id: String(id) } });

return res.status(200).json(invoice); }

The Secure Implementation

The fix moves the authorization check from the application layer to the data layer. By including the `userId` from a trusted server-side session in the database query, you prevent attackers from accessing records that do not belong to them. Never rely on client-side state or user-provided identifiers for authorization decisions. In Next.js Server Actions, the same principle applies: always fetch the current user's UID using `auth()` or `getServerSession()` before executing any database operations.

import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

export default async function handler(req, res) { const session = await getServerSession(req, res, authOptions); if (!session) return res.status(401).json({ error: ‘Unauthorized’ });

const { id } = req.query;

// SECURE: We filter by the resource ID AND the user ID from the session. // This ensures the database only returns the record if the user owns it. const invoice = await prisma.invoice.findFirst({ where: { id: String(id), userId: session.user.id } });

if (!invoice) { return res.status(404).json({ error: ‘Invoice not found or access denied’ }); }

return res.status(200).json(invoice); }

System Alert • ID: 2589
Target: Next.js API
Potential Vulnerability

Your Next.js API might be exposed to BOLA (Broken Object Level Authorization)

74% of Next.js apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.