next.js: Server Components fetch() throws in page.tsx

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: win32
      Arch: x64
      Version: Windows 10 Home
    Binaries:
      Node: 18.14.0
      npm: N/A
      Yarn: N/A
      pnpm: N/A
    Relevant packages:
      next: 13.2.3
      eslint-config-next: 13.2.1
      react: 18.2.0
      react-dom: 18.2.0

warn  - Latest canary version not detected, detected: "13.2.3", newest: "13.2.4-canary.4".
        Please try the latest canary version (`npm install next@canary`) to confirm the issue still exists before creating a new issue.
        Read more - https://nextjs.org/docs/messages/opening-an-issue

Which example does this report relate to?

async/await in Server Components

What browser are you using? (if relevant)

Opera

How are you deploying your application? (if relevant)

No response

Describe the Bug

In your page.tsx file. fetch() always throws : TypeError: Failed to parse URL from /api/getCards It also throws if you using axios.

Expected Behavior

As per example on website https://beta.nextjs.org/docs/data-fetching/fetching#asyncawait-in-server-components It uses the page.tsx file. error

It should work as expected. How it doesn’t.

To Reproduce

Create a page.tsxx And attempt the following code

import React from ‘react’; async function HomePageChild() { const data = await fetch(‘/api/getCards’) // throws “TypeError: Failed to parse URL from /api/getCards” return ( <> Child</> )

};

export default HomePageChild

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 1
  • Comments: 17 (2 by maintainers)

Commits related to this issue

Most upvoted comments

Same issue. In the meantime I’m using this that works in all my environments:

import { headers } from "next/headers";

// Inside the page component
const headersData = headers();
const protocol = headersData.get("x-forwarded-proto");
const host = headersData.get("host");
const data = await fetch(`${protocol}://${host}/api/hello`);

Any info to this? In development it is solved by using an absolute route (e.g. http://localhost:3000/api/hello) but if I want to deploy to Vercel, obviously this route would not work. I am using Node 16.8.0

Same issue here, using http://localhost:3000/... fixes it…

Running into the same issue