skip to Main Content

I have a nextjs application and when I execute a call to fetch a page from an external website if I do it from the backend via an API route everything works fine however when I do it from the frontend side I get a cors error.

This is the code from the API route:

async function getPage(url: string) {
    const response = await fetch(url);
    // do stuff
}

export async function POST(req: any) {
    const request = await req.json();
    try {
        await getPage(request.url);
        return NextResponse.json({ status: 200 });
    } catch (err: any) {
        console.log(err);
        return NextResponse.json({}, { status: 400, statusText: 'The website does not exist or is currently down.' });
    }
}

This is the same code in the frontend that is throwing an error:

async function getPage(url: string) {
    const response = await fetch(url, {
        mode: 'cors',
        headers: {
            'Access-Control-Allow-Origin': '*',
        }
    });
    // do stuff
}

const fetchPageFromSite = async () => {
        await getPage(url);
}

I am using the fetchPageFromSite inside a useEffect.

3

Answers


  1. This should help you CORS error with jquery. By the way almost always this error fixes from the server side

    Login or Signup to reply.
  2. The concept of CORS – Cross Origin Resource Sharing – is applicable only on the client side. When you are sending request from the server (api route), the url you are fetching from doesn’t know about the origin or domain of your website. Thus, your call from api route works without any errors.

    Login or Signup to reply.
  3. CORS must be manage from Back-End (the external website you want to fetch).

    Because Back-end of that website need to allow Cross Origin to your page or all (*).

    You can find more details about CORS here https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search