Nextjs fetching data from child component

23 views Asked by At

I have page.tsx component where I need to get the current pathname, so it's a client component. Then I have a child server component where I would like to fetch data based on the pathname passed as prop. However, when I try to fetch the data I get these errors:

Uncaught (in promise) Error: Failed to fetch data. at fetchRadio

Access to fetch at 'https://api.example.com' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

The parent component:

"use client";

import * as React from "react";
import Radio from "@/components/ui/radio/radio";
import { usePathname } from "next/navigation";

export default function Page() {
    const pathName = usePathname();

    return <Radio pathName={pathName} />;
}

Child server component:

import * as React from "react";
import { fetchRadio } from "@/lib/data";

export default async function Radio({ pathName }: { pathName: string }) {
    const radio = await fetchRadio(pathName);

    return (
        {/* ... */}
    );
}

Fetch function:

export async function fetchRadio(pathName: string){
    try {
        const radios = await fetch("https://api.example.com");
        const data = await radios.json();

        console.log(pathName); // for now I just want to log the pathname
    } catch (error) {
        console.error("Error:", error);
        throw new Error("Failed to fetch data.");
    }
}
1

There are 1 answers

3
AshkanYadegari On

Hmm this is not really a NextJS issue, but a CORS issue. Client side request get's blocked directly by the browser since https://api.example.com does not allow cross-origin requests. Your localhost being not the same origin as example.com.

One way to fix it, usually 3rd party API's have a CORS management section where you can whitelist your localhost or your domain name for specific requests.