Skip to content

Middleware does not work with API Endpoints #7070

@alex-sherwin

Description

@alex-sherwin

What version of astro are you using?

2.4.4

Are you using an SSR adapter? If so, which one?

NodeJS

What package manager are you using?

pnpm

What operating system are you using?

Mac

What browser are you using?

Chrome

Describe the Bug

If you have an API Endpoint which returns a Response with ANY non-null body, middleware is skipped entirely and prints warning:

Middleware doesn't work for endpoints that return a simple body. The middleware will be disabled for this page.

This is caused by this line of code:

if (response.body === null) {

I can't think of why there's a conditional block around whether to run middleware or not for API Endpoints, but I'm pretty confident that this is not the intended behavior.

Maybe this conditional was trying to naively determine if response was of the optional EndpointOutput object instead of a Response? But that doesn't seem likely since in the code path which does call the middleware types the middleware generics to expect the union type of Response | EndpointOutput.

It feels to me like the conditional around running middleware for API Endpoints should probably be removed entirely and just always run if middleware is defined.

However, if there is some legitimate some reason why middleware should be skipped, I don't think it should be based on whether Response.body is set or not, I don't think middleware should care about this for any particular reason

Link to Minimal Reproducible Example

https://stackblitz.com/edit/github-avaykm-qoanvo?file=src/pages/api-notok.ts

Participation

  • I am willing to submit a pull request for this issue.

Metadata

Metadata

Assignees

Labels

- P3: minor bugAn edge case that only affects very specific usage (priority)

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions