Skip to main content

SKY-D280 · Security in code

Next.js API route changes data without checking the user

High

A Next.js API route is a server function that answers HTTP requests, such as POST in app/api/posts/route.ts or the handler in pages/api/. SKY-D280 reports a route that handles POST, PUT, PATCH or DELETE and changes data without first checking, in the route itself, that the caller is logged in.

Languages
TypeScript/JavaScript
Quality gate
counted toward the gate limits (full and diff scans)
Finding type
review
Catalog name
Next.js mutating API route missing authentication
Wrong result? Report itA false positive, a missed case or a confusing message: it goes privately to the founder.

Why it matters

Every API route is a public URL. Without a check, anyone can create, change or delete records with one fetch() call, and the login page of the app does nothing to stop them.

What Skylos flags

app/api/posts/route.ts · TypeScriptReported on line 5
import { NextResponse } from "next/server"; import { db } from "@/lib/db"; export async function POST(request: Request) {  const body = await request.json();  const post = await db.post.create({ data: { title: body.title, text: body.text } });  return NextResponse.json(post, { status: 201 });}

What Skylos leaves alone

app/api/posts/route.ts · TypeScript
import { getServerSession } from "next-auth";import { NextResponse } from "next/server"; import { db } from "@/lib/db"; export async function POST(request: Request) {  const session = await getServerSession();  if (!session) {    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });  }  const body = await request.json();  const post = await db.post.create({ data: { title: body.title, text: body.text } });  return NextResponse.json(post, { status: 201 });}

Why Skylos leaves it alone

getServerSession from next-auth is a known authentication call. Its result is awaited, and the route returns 401 when there is no session, before db.post.create() runs.

More languages

JavaScript

Flagged

pages/api/comments/[id].js · JavaScriptReported on line 4
import { db } from "../../../lib/db"; export default async function handler(req, res) {  if (req.method === "DELETE") {    await db.comment.delete({ where: { id: req.query.id } });    return res.status(204).end();  }  const comment = await db.comment.findUnique({ where: { id: req.query.id } });  return res.status(200).json(comment);}

Not flagged

pages/api/comments/[id].js · JavaScript
import { getToken } from "next-auth/jwt"; import { db } from "../../../lib/db"; export default async function handler(req, res) {  if (req.method === "DELETE") {    const token = await getToken({ req });    if (!token) {      return res.status(401).json({ error: "Unauthorized" });    }    await db.comment.delete({ where: { id: req.query.id } });    return res.status(204).end();  }  const comment = await db.comment.findUnique({ where: { id: req.query.id } });  return res.status(200).json(comment);}

Why Skylos leaves it alone

In the Pages Router the method branch is the route. The DELETE branch awaits getToken from next-auth/jwt and returns 401 without a token before deleting. The GET part does not change data, so it needs no check.

How Skylos decides

  1. Runs with --danger on TypeScript and JavaScript route files: route.ts, route.tsx, route.js or route.jsx under an app/ folder, and files under pages/api/.
  2. Finds mutating routes: an exported POST, PUT, PATCH or DELETE function in the App Router, or a req.method === "POST" style branch in a Pages Router handler. GET routes are not checked.
  3. Accepts a route as protected only when a trusted authentication call runs before every data change in it: getServerSession (next-auth), getToken (next-auth/jwt), auth or currentUser (@clerk/nextjs), Clerk auth.protect(), or an auth export of a local file proven to be an Auth.js setup.
  4. The call must be awaited, its result kept in a variable, and a check such as if (!session) return … or throw must reject the request on every path before the change. A result that is never checked, or a check inside a branch, does not count.
  5. A project helper counts as well: a function imported from the project (./lib/request, @/lib/auth) whose source, followed through its own calls and imports (up to 4 calls deep, 12 files), reaches a recognised verification such as jsonwebtoken/jose verify, next-auth, Clerk, iron-session, Supabase getUser or Firebase verifyIdToken. Its awaited result must be rejected on failure: const { auth, error } = await parseRequest(request); if (error) return error();. A call with skipAuth: true proves nothing.
  6. An explicit authorization check also counts: if (!(await canUpdateWebsite(auth, id))) return unauthorized(); (or a 401/403/404 status or throw) before the change. Schema building (z.object(...)), request reads and return notFound()-style responses are not data changes.
  7. A POST route on a webhook path (for example api/stripe/webhook) that reads the request body is left to SKY-D282. When the file could not be fully analysed, a file that looks like a mutating route is still reported, because the check could not be proven.

How to fix it

Call your authentication library at the top of the handler, stop with 401 when there is no user, and only then read the body and change data. Check ownership too when one user must not edit another user's records.

app/api/posts/route.ts · TypeScript · the fix, against the flagged file
Added: import { getServerSession } from "next-auth";import { NextResponse } from "next/server"; import { db } from "@/lib/db"; export async function POST(request: Request) {Added:   const session = await getServerSession();Added:   if (!session?.user?.email) {Added:     return NextResponse.json({ error: "Unauthorized" }, { status: 401 });Added:   }  const body = await request.json();Removed:   const post = await db.post.create({ data: { title: body.title, text: body.text } });Added:   const post = await db.post.create({Added:     data: { title: body.title, text: body.text, author: session.user.email },Added:   });  return NextResponse.json(post, { status: 201 });}

When it can be wrong

  • Your own helper, such as const user = await requireUser() from @/lib/session, is not a trusted authentication call, so the route is still reported even when the helper checks the session.
  • Protection in middleware.ts is not seen; only checks inside the route count. Routes meant to be public, such as a sign-up or contact form, are reported too.

Seeing a case that isn't listed here? Report the wrong result so the rule can be fixed. Don't paste company code: describe the shape of it.

How to silence it

  • Mark the line the finding points at (the exported function or the method branch) and say what protects the route.

    TypeScript
    export async function POST(req: Request) { // skylos: ignore[SKY-D280] signup form
  • [tool.skylos] ignore = ["SKY-D280"] turns the rule off for the whole project.

  • skylos baseline . and then --baseline accept today's routes and report only new ones.

From the Skylos rule handbook, Skylos 5.8.0 (commit 5b880b0). All rules.