Next.js Discord

Discord Forum

Fetch from API route not working

Unanswered
Britannia Petite posted this in #help-forum
Open in Discord
Avatar
Britannia PetiteOP
Hello,
This is probably a very elementary question. I'm using Deno. I've set up an API route at URL /api/exchange, and from file src/app/page.tsx, I fetch from the route, but it results in the following error:

 ⨯ TypeError: Invalid URL: '/api/exchange/'
    at getSerialization (ext:deno_url/00_url.js:98:11)
    at new URL (ext:deno_url/00_url.js:405:27)
    at new Request (ext:deno_fetch/23_request.js:329:25)
    at eventLoopTick (ext:core/01_core.js:175:7)


Here's my code:
import { Rate } from "./api/exchange/route";

const Rates = async () => {
  const response = await fetch("/api/exchange/");

  const formatted = response.json() as unknown as {
    rates: Rate[];
  };

  if (!response) return <h1>works</h1>;
  else return <p>does not work</p>;
};

export default function Home() {
  return (
    <body className="bg-white text-black dark:bg-black dark:text-white">
      <div className="font-mono align-left m-10 sm:m-6 lg:m-16">
        <h1 className="text-[6vh] leading-[1]">Exchange rates</h1>
        <br />
        <Rates />
      </div>
    </body>
  );
}


Thanks in advance. I'm probably doing something very wrong.

1 Reply

Avatar
Bengal
You're using fetch in a server component, meaning you're using the node fetch. Based on the error, it's the deno implementation of the node fetch.

Couple of things to unwrap, you don't need to call your own API from a server component. Since your server component is rendered on the server, you can quite literally copy/paste the code from your API route in your Home/Rates components and it will work. Typically, your Next.js API would be used from client components.
As for the error itself, I'm not sure what the deno implementation is, maybe the trailing slash is causing the problem or maybe it needs the entire URL? Regardless, I wouldn't recommend proceeding that way