Guides / Next.js route handlers without auth
Next.js API route handlers with no authentication check: how to find and fix them
A Next.js Route Handler is a public-facing API endpoint. Unless access is restricted somewhere, it answers anyone who knows the URL, signed in or not. Your login page and your hidden buttons do not change that. This guide shows how to inventory your handlers, test them safely, and enforce a server-side check that also confirms the caller owns the record. It follows the current Next.js 16 App Router documentation.
The short answer
Every method in a route.ts or route.js file that reads or changes private data must enforce authentication and authorization before it touches that data. The check can sit in the method itself or in a server-only helper it calls, such as a Data Access Layer. Next.js says it plainly in its authentication guide: treat Route Handlers "with the same security considerations as public-facing API endpoints, and verify if the user is allowed to access the Route Handler." A missing inline call is a review signal, not proof that the data is exposed. A hidden button or a login page is not protection.
RouteContext becomes global after next dev, next build or next typegen. If Cache Components is enabled, follow its separate Route Handler caching rules rather than assuming the force-static example below applies.Next.js lets one file export GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, and each one is its own entry point. A file that checks the session in GET but not in DELETE has no protection for deletes unless something else provides it. A common slip is a page that redirects signed-out visitors while the API route behind it never looks.
The same rule applies to Server Actions. Next.js notes that an exported Server Action "is reachable via a direct POST request, not just through your application's UI" and that you should verify authentication and authorization inside each one. If your app uses Clerk, the guide on protecting Clerk API routes covers the Clerk-specific calls. This page is about the check itself, whichever sign-in library you use.
Why a login page or Proxy is not enough
- Hidden UI is not a lock. The route is a URL. Anyone can send a request to it with curl, a browser address bar or a script, without ever loading your pages, unless something on the server stops them.
- Proxy is a first filter, not the lock. Starting with Next.js 16, Middleware is called Proxy. The docs say Proxy "should not be used as a full session management or authorization solution," and the authentication guide says it "should not be your only line of defense." They recommend doing the majority of security checks "as close as possible to your data source."
- Check your matcher. The sample Proxy matcher in the authentication guide is
'/((?!api|_next/static|_next/image|.*\\.png$).*)', which leaves/apiout. If you copied a matcher like that, Proxy is not even running on your API routes, so the handler has to do the work. - A page check does not cover the action or route behind it. Next.js says a page-level check "does not extend to the Server Actions defined within it" and that the action "is a separate entry point and must verify the caller on its own." Treat a Route Handler the same way: it is its own entry point.
How to check
1. Inventory every route file
Route Handlers live in route.js or route.ts files inside the app directory. From the project root, list the files:
find app src/app -type f \( -name 'route.ts' -o -name 'route.js' \) 2>/dev/null
Then open each file and each file it re-exports from. Look for GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, including handlers exported as constants or wrapped in a helper. A text search for export function misses those forms, so treat grep as a heuristic, not a complete inventory. An unsupported method can return 405 Method Not Allowed, but do not work out the export list from a status code: Next.js automatically implements OPTIONS when a file does not define it. If you also have an older pages/api folder, list it separately. Next.js says Route Handlers are the equivalent of API Routes in the pages directory.
2. Trace where each method checks
For each method that reads or changes private data, find where it verifies the caller. It may call your helper directly, or an imported wrapper or Data Access Layer may do it. Read those helpers too. A quick list of route files that never mention your helper (replace getSession with whatever yours is called, such as auth, verifySession or getServerSession) is a place to start looking:
grep -rL --include='route.ts' --include='route.js' 'getSession' app src/app 2>/dev/null
Each file in that list is either meant to be public (a health check, a payment webhook that verifies its own signature), protected through a wrapper you have not traced yet, or a gap. Trace imported wrappers and Data Access Layer calls before you decide which. A file that does mention the helper still needs a look: confirm the check runs before the data is touched in every method, not just the first one.
3. Test with controlled records
Warning. POST, PUT, PATCH and DELETE requests can create, change or permanently delete data and can trigger downstream actions such as payments or email. curl -X sends the real method, not a dry run. Prefer a local or staging copy with disposable records and external side effects switched off. If you must test production, get authorization first, use disposable test records only, and have a recovery plan. Do not run these commands against real user records. Only test apps you own, and never print or share real private data, cookies or tokens.
Use your app while signed in and note the /api/... requests in the browser's Network tab, so you know what a valid request looks like. Then send valid requests (a real body for write methods, an id of a test record you created) signed out, as the record's owner, and as a different signed-in user. This example prints only the status code:
# Local or staging, disposable test record only.
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3000/api/projects/TEST_ID
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE http://localhost:3000/api/projects/TEST_ID
The curl http_code variable is the numerical response code from the last transfer, and nothing more. On an endpoint meant to be private, a 2xx answer to a signed-out request deserves investigation: look at what the response actually contained and whether the test record changed. A 204 can also mean nothing happened. A 400, 404 or 405, a redirect or another error does not prove authorization works either, because a bad request body can fail before the check is reached. Next.js's own example returns 401 when there is no session and 403 when the user lacks permission. For signed-out and non-owner requests, confirm there is no private data in the response and the disposable test record is unchanged. For the authorized owner control, confirm the expected response or intended change occurs; in the DELETE example, the disposable record should be deleted. Use a fresh disposable record when needed so an earlier successful owner request does not invalidate a later denial test.
4. Look for handlers that trust an id from the request
grep -rnE --include='route.ts' --include='route.js' '(userId|user_id|ownerId)' app src/app 2>/dev/null
A resource id in the URL, such as a project id, is normal. The question is whether the handler authorizes it against the verified session before reading or changing anything. Next.js's own safe example accepts a postId and then checks that post.authorId matches the session user. Be wary where the acting identity itself comes from the URL, query string or body: take the user id from the verified session on the server, and do not treat a submitted owner or user id as proof of permission. This search is only a starting point. A match is a prompt to read the code, not a finding.
How to fix it
1. Put one session helper on the server
Next.js recommends a Data Access Layer: an internal, server-only module that performs authorization checks and returns minimal data. Keep the session check in one place and call it from every handler. Here getSession is your own helper. It reads and verifies your session and returns null when there is none. Next.js's authentication guide shows one way to build it with a signed cookie and the server-only package, and an auth library does the same job.
2. Check the session, then check ownership
// app/api/projects/[id]/route.ts
import { getSession } from '@/lib/session'
import { db } from '@/lib/db'
export async function DELETE(
_req: Request,
ctx: RouteContext<'/api/projects/[id]'>
) {
const session = await getSession()
if (!session) return new Response(null, { status: 401 })
const { id } = await ctx.params
const project = await db.project.findUnique({ where: { id } })
if (!project) return new Response(null, { status: 404 })
if (project.ownerId !== session.userId) {
return new Response(null, { status: 403 })
}
await db.project.delete({ where: { id } })
return new Response(null, { status: 204 })
}
Two checks, on purpose. The first asks "is anyone signed in" and returns 401. The second asks "does this user own this record" and returns 403. Next.js separates them the same way: authentication is "is the user logged in," authorization is "does this user have permission to act on this specific resource," and skipping the second leaves you open to Insecure Direct Object Reference (IDOR) bugs, where changing an id in the request reaches another user's data. In a dynamic route, the params value is a promise, so await it as shown.
3. Cover every method that touches private data
Make sure GET, POST, PUT, PATCH and DELETE alike enforce the check before they read or change anything private, and do the same for HEAD if you export it. Putting the check in a shared helper keeps this short, which is the point of the Data Access Layer: it centralizes the logic and reduces the risk of authorization bugs.
4. Keep per-user data out of cached GETs
In the current docs, Route Handlers are not cached by default, but you can opt a GET into caching, for example with export const dynamic = 'force-static'. The default for GET changed in Next.js 15, so on Next.js 14 check your own version's behavior instead of relying on this. With Cache Components enabled, different rules apply. Whatever your version, only cache responses that are the same for everyone. Anything that depends on the signed-in user should stay dynamic.
Prove it / common mistakes
- Checking in
GETonly. TestPOST,PUT,PATCHandDELETEtoo, on disposable records as described above. Each exported method is separate. - Trusting a hidden button. If the delete button only shows for admins, the route still has to refuse everyone else.
- Authentication without ownership. A signed-in user who can change an id in the URL can read a neighbor's record. Sign in as user B and try to reach user A's test record by changing the id. You should get a refusal, such as the 403 in the example, and the record should be unchanged.
- Relying on Proxy alone. Keep Proxy for quick redirects if you like. The handler still checks.
- Forgetting Server Actions. Re-verify the user inside each
'use server'function. They can be reached by a direct POST too. - Public routes by accident. A webhook or health route can stay open, but write down which ones are public on purpose, and make webhooks verify a signature. See Stripe webhook signature verification.
- Re-test after the fix. Repeat the same tests on disposable records: signed out should be refused (401 in the example), a second signed-in user should be refused (403) on someone else's record, and no private data or record changes should result.
Do not "fix" this by hiding the route. An unlinked URL, a guessable-only id or a client-side check is not a lock. The server has to say no.
next step
Want a second pair of eyes?
Grab the free Lockdown Pack (security rules for Cursor and Claude Code plus a pre-launch checklist), or have us check your repo with a $99 Scan + Report.
Sources
Every Next.js detail above was checked against these official pages. Last checked Nov 2026. If behavior changed, the docs below are the source of truth.
- Next.js: How to implement authentication (Route Handlers are public-facing API endpoints; 401 and 403 example; Data Access Layer; Proxy is not the only line of defense; sample matcher excludes api)
- Next.js: Data security (Data Access Layer; Server Actions reachable by direct POST; re-verify inside each action; IDOR and ownership check)
- Next.js: Route Handlers (route.js|ts convention; supported HTTP methods; 405; caching and force-static; RouteContext; Cache Components)
- Next.js: route.js reference (params is a promise; OPTIONS is implemented automatically when not defined; version history for the GET caching default; types generated by next dev, next build or next typegen)
- Next.js: Proxy (renamed from Middleware in Next.js 16; not a full authorization solution)
- curl man page (-X sends the method you give it; the http_code write-out variable is the numerical response code)