Make serverside fetch work seamlessly with API routes
See original GitHub issueFeature request
Is your feature request related to a problem? Please describe.
Next.js provides API handlers under /api
. It’s suboptimal to call these handlers with fetch
during SSR because:
- You’d need to come up with an absolute url, since on the server there is no concept of origin.
- even if you return a JSON object in the handler through
res.json
, if you usefetch
it will have to be serialized, and deserialized. Increasing CPU and memory usage. - it will hit the network, adding latency and a higher risk of failures.
Describe the solution you’d like
I’d like next.js to provide a fetch
polyfill serverside only, that is capable of calling api handlers without hitting the network. For instance, take the following code:
Page.getInitialProps = async () => {
const posts = await fetch('/api/posts');
return { posts };
};
This just works out of the box client side, and I think it should do as well serverside. Concretely, I think serverside the following should happen:
- if the url doesn’t start with
/api/
just call regularfetch
with the same arguments - otherwise, dynamically import (or
require
) the API handler:
(take rewrites into account, etc…)const { default: handler } = import(projectRoot + '/pages/api/posts')
- convert the
fetch
arguments into anNextApirequest
and mock aNextApiResponse
that produces a fetchResponse
. call thehandler
with these and return aResponse
promise. i.e. theres.json(body)
can directly pipe toresponse.json()
etc…
This could even be extended to all urls next.js answers to, like public folder files, pages,…
Describe alternatives you’ve considered
I’ve tested a POC in a small project and it seems to be possible. a quick check yielded a performance improvement from ~10ms to <0.1ms to fetch a resource serverside. What’s not possible is creating a fetch polyfill as a node module that does this for you because it needs to know the location of the pages folder. And it would need to replicate the next.js routes rewriting behavior. That’s why it makes more sense to implement in next itself, it would complement the API routes feature nicely.
Additional context
alternative to https://github.com/zeit/next.js/issues/10266 as per comment:
We unfortunately can’t add this to Next.js as it’s insecure to read the host header on many hosting providers. So I’ll close the feature request as there is no secure way to introduce this feature.
I think this would be the secure and performant way of implementing this feature.
If lack of bandwidth would be the reason not to implement this, I’d be happy to contribute.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:5 (5 by maintainers)
Top GitHub Comments
oh right, ofcourse 👍
This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.