Encountering a CORS error while attempting to initiate a Github API call on my Next App

I'm currently developing a Next.js React app with TypeScript and I am wondering if I need a server to make requests to the GitHub API. In my next.config.mjs file, as shown below, the only task my app needs is to fetch content from a file in a public repo on GitHub.

const nextConfig = {
    async headers() {
        return [
            {
                source: "/:path*",
                headers: [
                    { key: "Access-Control-Allow-Credentials", value: "true" },
                    { key: "Access-Control-Allow-Origin", value: "*" },
                    { key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,POST,PUT" },
                    { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
                ]
            }
        ]
    }
}

Here's the code snippet for the API call:

 useEffect(() => {
        const fetchCode = async () => {
            const response = await fetch(`https://api.github.com/repos/Kanav-Arora/DSA-Guide/contents/Binary Search/binary_search.cpp`, {
                headers: {
                    Authorization: `Bearer ${github_api}`,
                },
                method: 'get',
                mode: 'cors',
            });
            console.log(response);
        }
        fetchCode();
    }, [cpp])

The error received is:

Response {type: 'cors', url: 'https://api.github.com/repos/Kanav-Arora/DSA-Guide/contents/Binary%20Search/binary_search.cpp', redirected: false, status: 401, ok: false, …}

I have attempted to configure CORS settings but the GitHub API still does not work in the development environment, even though it functions correctly in Postman.

Answer №1

Please transfer this code to a route.ts file.

If you leave it in the useEffect, it may expose sensitive information to users.

To avoid this, consider creating an API Route and utilize the fetch API to retrieve data on the client side (if necessary).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can the panel within an accordion be enlarged or minimized?

Currently, I am implementing an accordion feature with the option to expand or collapse all panels using two buttons. My goal is to allow users to manage each panel within the accordion individually. However, I have encountered an issue that needs attenti ...

Despite EsLint and Prettier's efforts to improve code quality, users are experiencing frequent unnecessary errors and unexpected auto-insertion of parentheses at

When working with redux saga for handling asynchronous calls, I encountered an issue. After making an API call and storing the retrieved data in local storage, eslint/prettier automatically adds parentheses to the assignment operator at the end of the line ...

The error message, "Property 'message' is not found on type 'ErrorRequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>.ts(2339)", indicates that the requested property is not present in the specified type

Hello there! Recently, I implemented a custom error handling middleware in my Node.js TypeScript application. However, I encountered an issue where it is showing an error stating that 'message' does not exist on type 'ErrorRequestHandler&apo ...

Encountered an error of 'No overload matches this call' while configuring ContextApi alongside useReducer with Typescript

I am currently setting up ContextApi and useReducer with typescript. I am encountering an error with my "issuesInitialState" variable in useReducer, where I receive the following message: No overload matches this call. Overload 1 of 5, '(reducer: ({ ...

The combination of TypeScript output is not working as expected

Here is my current configuration: tsconfig.json { "compileOnSave": true, "compilerOptions": { "module": "none", "outFile": "js/app.js" } } MyApp.Main.ts class Main { constructor() { Utilities.init(this); ...

When a reaction function is triggered within a context, it will output four logs to the console and

My pokemon API application is encountering some issues. Firstly, when I attempt to fetch a pokemon, it continuously adds an infinite number of the same pokemon with just one request. Secondly, if I try to input something again, the application freezes enti ...

I'm having an issue with my NextJS timer where it doesn't stop and ends up going into negative numbers. Any

Here is the code snippet for my timer component. It fetches the 'createdAt' prop from the database and functions correctly. However, I have encountered an issue where the timer does not stop at 0 but continues running indefinitely. I attempted to ...

Angular 2 failing to recognize service variable changes initiated from component

Hello there, I'm currently facing a challenge with updating my component to reflect the correct value of a service variable whenever it changes. Here's what I have so far: Snippet from Component1 HTML {{icons | json}} Component1 Code icons: ...

You were supposed to provide 2 arguments, but you only gave 1.ts(2554)

Hey everyone, I hope you're having a good morning. Apologies for the inconvenience, I've been practicing to improve my skills and encountered an issue while working on a login feature. I'm trying to connect it to an API but facing a strange ...

Postpone the initial click action triggered by the specified directive

Is it possible to create a directive that prompts for confirmation when a button is clicked? This would involve storing the original event and only executing it once the user confirms their choice. A similar behavior has been mocked here: https://stackbl ...

Sharing Properties Across Angular Components using TypeScript

Seeking a solution for storing properties needed in multiple components using a config file. For example: number-one-component.ts export class NumberOneComponent { view: any[]; xAxis: number; yAxis: number; label: string; labelPositio ...

Angular Navigation alters the view

I want to navigate to a different page using Angular routing, but for some reason it's not working. Instead of moving to the designated Payment Component page, the content is staying on my Main Component. Why is this happening? app.routing.module.ts ...

Assistance with the Chakra UI Range Slider in React

I could use some help figuring out where exactly to implement my OnChange and Map functions for mapping JSON data into a Range Slider. Everything seems to be rendering correctly, but I keep encountering an error when I try to move the slider: Unhandled Ru ...

Exploring ways to integrate Email.js CDN into Next.js framework

Struggling to find a clear solution on how to correctly import this. I have installed Email JS via NPM and attempted to import it using the HEAD tag. <Head> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/ema ...

What specific type of useRef should I use to reference a callback function?

I have been exploring the method outlined by Dan Abramov for creating a custom hook to handle basic setInterval functionality. However, I am facing challenges while trying to type it in TypeScript. Specifically, I am unsure about what should be the type of ...

Tips for manually inputting dates in Primeng Calendar Datepicker with the slash "/" symbol

I need assistance with adding slashes to manual input when using the primeng Calendar component. <p-calendar [monthNavigator]="true" [yearNavigator]="true" yearRange="1950:2021" ngModel [required]="tru ...

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...

What are some ways to control providers in targeted tests using ng-mocks?

I recently started utilizing ng-mocks to streamline my testing process. However, I am struggling to figure out how to modify the value of mock providers in nested describes/tests after MockBuilder/MockRender have already been defined. Specifically, my que ...

What could be causing the "ERROR TypeError: Cannot read property 'length' of undefined" message to occur with a defined array in my code?

Even though I defined and initialized my array twice, I am encountering a runtime error: "ERROR TypeError: Cannot read property 'length' of undefined." I have double-checked the definition of the array in my code, but Angular seems to be playing ...

Retrieve the overall number of job openings from the Github Job API

I have successfully created an Angular application that mirrors the functionality of However, I encountered a limitation where only 50 positions are available per page, To fetch additional jobs beyond the initial 50, I need to append "?page=X" to another ...