Skip to content

API authentication using the middleware doesn't response a 401 #13102

Open
@pacoorozco

Description

@pacoorozco

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"}% 

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingtriageUnseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions