question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Make serverside fetch work seamlessly with API routes

See original GitHub issue

Feature 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:

  1. You’d need to come up with an absolute url, since on the server there is no concept of origin.
  2. even if you return a JSON object in the handler through res.json, if you use fetch it will have to be serialized, and deserialized. Increasing CPU and memory usage.
  3. 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:

  1. if the url doesn’t start with /api/ just call regular fetch with the same arguments
  2. otherwise, dynamically import (or require) the API handler:
    const { default: handler } = import(projectRoot + '/pages/api/posts')
    
    (take rewrites into account, etc…)
  3. convert the fetch arguments into an NextApirequest and mock a NextApiResponse that produces a fetch Response. call the handler with these and return a Response promise. i.e. the res.json(body) can directly pipe to response.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:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:5 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
Janpotcommented, Jan 27, 2020

oh right, ofcourse 👍

0reactions
balazsorban44commented, Jan 30, 2022

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Make serverside fetch work seamlessly with API routes #10272
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...
Read more >
Internal API fetch with getServerSideProps? (Next.js)
It can be tempting to reach for an API Route when you want to fetch data from the server, then call that API...
Read more >
Fetch data from an API on the server-side with ... - Egghead.io
In this lesson, we will learn how to use getServerSideProps to dynamically fetch data and server-side render pages by consuming a "user profile"...
Read more >
Fetching data from the server - Learn web development | MDN
This article shows how to start working with Fetch to fetch data from the server.
Read more >
Create Pages & Fetch Data in Next.js Using Static & Dynamic ...
... create static and dynamic routes in Next.js and fetch dynamic data to build a variety of pages. We'll use The Last Airbender...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found