nextauthjs / nextauthjs/next-auth

API authentication using the middleware doesn't response a 401

Open
#13,102 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug triage
Dominant language
TypeScript
Stars
28.4k
Forks
4k
PR merge metrics
No merged PRs in 30d

Description

Environment

  System:
    OS: Linux 6.8 Ubuntu 24.04.2 LTS 24.04.2 LTS (Noble Numbat)
    CPU: (8) x64 11th Gen Intel(R) Core(TM) i7-1185G7 @ 3.00GHz
    Memory: 22.22 GB / 31.06 GB
    Container: Yes
    Shell: 5.2.21 - /bin/bash
  Binaries:
    Node: 22.17.0 - /run/user/1000/fnm_multishells/468830_1752159406675/bin/node
    npm: 10.9.2 - /run/user/1000/fnm_multishells/468830_1752159406675/bin/npm
  Browsers:
    Chrome: 138.0.7204.100
  npmPackages:
    next: 15.3.5 => 15.3.5 
    next-auth: ^5.0.0-beta.29 => 5.0.0-beta.29 
    react: ^19.0.0 => 19.1.0 

Reproduction URL

https://github.com/pacoorozco/next-auth-v5-testing-route-handlers/tree/main/src/app/api/protected-with-middleware

Describe the issue

When configuring the middleware to authenticate API routes, the un-authenticated flow redirects to the login page instead of responding with a 401 error code.

How to reproduce

Follow the instructions of this README and do a curl to /api/protected-with-middleware

A redirect to the login page is seen:

$ curl "http://localhost:3000/api/protected-with-middleware"   
/api/auth/signin?callbackUrl=http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fprotected-with-middleware%  
Expected behavior

A 401 error would be expected:

< HTTP/1.1 401 Unauthorized
< 
* Connection #0 to host localhost left intact
{"message":"Not authenticated"}% 

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked reproduction repository and its README, then inspect the middleware protecting /api/protected-with-middleware. Run the documented curl request without authentication and trace why it redirects to /api/auth/signin. Done means the unauthenticated API request returns HTTP 401 with the expected JSON message instead of a login redirect.

Written by the indexing model from the issue text.

Assessment

Tech stack
next.js, typescript
Domain
api, authentication
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.