Encountering a CORS issue specifically on the client side of a Next.js application when interacting with an API gateway

I've been struggling with this issue for a week now and can't seem to fully describe it. I have a FastAPI server running as a Lambda connected to API Gateway.

https://i.stack.imgur.com/S5Zx9.png

Both FastAPI and API Gateway have CORS enabled, but I'm facing CORS errors on my client side while NextJS requests work fine.

The API endpoint is api.example.com/api, and the app is example.com.

Attempts Made:

  • Tried adding specific headers to each request like
    "Access-Control-Allow-Origin": '*', "Access-Control-Allow-Headers": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version", "Access-Control-Allow-Methods": 'GET, POST, PUT, DELETE, OPTIONS'
  • Attempted re-writes to create a proxy setup
  • Used a CORS Chrome extension, but no luck

The signup route done by Next works, but the client requests do not.

https://i.stack.imgur.com/dErCf.png

Error in Client Requests:

https://i.stack.imgur.com/aqkav.png

I've tried several other things but nothing seems to work. This is the code for creating the Axios Instance (even without headers):

import axios from 'axios';


export const api = (session: any): any => {
    const headers: { [key: string]: string | number } = {
        "Accept": 'application/json',
    }

    if (session?.user) {
        headers.Authorization = session.user.token;
    }

    const api = axios.create({
        baseURL: process.env.NEXT_PUBLIC_API_DOMAIN,
        withCredentials: true,
        headers
    });


    return api;
};

Any assistance would be greatly appreciated.

EDIT:

Error Details:

https://i.stack.imgur.com/zZ394.png

The Lambda doesn't seem to receive requests from the client, only from the NextJS backend. It could be an issue with API Gateway configuration or client request headers setup.

Additional attempts made:

  • Added Access-Control-Allow-Credentials header as true on both client and API gateway.
  • Included a specific set of origins in my FastAPI CORS middleware with https://example.com

Answer №1

Figured it out! If you're facing CORS problems with API Gateway and the Access-Control-Allow-Credentials header, make sure your Integration Request is not set to Mock. In my case, this configuration was causing issues.

I even had a 40-minute call with an AWS expert (paid service) and we overlooked this simple detail - what a bummer!

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

Database storing incorrect date values

After successfully displaying the current year and month in a textbox, an issue arises when submitting the data to the database. Instead of the expected value from the textbox, it defaults to 2014. What could be causing this discrepancy? function YearM ...

Save a customized JavaScript file and integrate it into a Vue component

As a newcomer to Vue.js, I have a question regarding calling functions from a custom JavaScript file within a Vue component. Here is what I attempted: custom.js class API{ function testCall(){ alert("test ok"); } } export {API} App.vue ...

Typescript is missing Zod and tRPC types throughout all projects in the monorepo, leading to the use of 'any'

Recently, I've found myself stuck in a puzzling predicament. For the last couple of weeks, I've been trying to troubleshoot why the types are getting lost within my projects housed in a monorepo. Even though my backend exposes the necessary types ...

Is there a way to simultaneously apply the :active pseudoclass to multiple elements?

<div id="a">A</div> <div id="b">B</div> <div id="c">C</div> <style> #a, #b, #c { height: 100px; width: 100px; background-color:red; font-size: 100px; margin-bottom: 20px; } ...

Modify the useRef value prior to the HTML rendering (React functional component)

Hello everyone, I am attempting to update the value of useRef before the HTML is rendered. I have tried using useEffect for this purpose, but it runs after the HTML is ready, making it unsuitable for my needs. What I want to achieve is resetting the value ...

Express js is not returning a value from a recursive function?

I've been working on an ecommerce website where I created a mongoose model for all categories. However, the challenge arises when dealing with subcategories that require a parent id in the database. When a request is made, all categories are retrieved ...

Error: Papa is not defined. The file was loaded from the CDN in the header section

I have integrated the cdn hosted lib for PapaParse in my HTML header. However, when I execute my JavaScript file and it reaches the function where I call Papa.unparse(data); It throws an error stating that Papa is undefined. This has left me puzzled as I h ...

What is the method to retrieve a client's IP address within Next.js 13?

I am working on a next.js 13 application and I need to integrate an API endpoint /api/getIP. The file route.js can be found at /app/api/getIP/route.js. To see the Minimal Reproduceable Code, visit: https://github.com/Nusab19/nextjs-test/tree/main/app I ...

Angular JS Sorting Wordpress Plugin allows users to easily organize and sort content

Seeking some assistance here, any help would be greatly appreciated. Currently using a Wordpress Angular JS plugin that is causing some unusual alphabetical sorting. This snippet of code showcases the taxonomy: <!-- for taxonomy --> <div ng-if ...

Implementing a New Port Number on a ReactJs Local Server Every Time

As a newcomer to ReactJS, I recently encountered an issue while working on a project that puzzled me. Every time I shut down my local server and try to relaunch the app in the browser using npm start, it fails to restart on the same port. Instead, I have ...

Passing JSON information from a website to a Node.js server

<script type="text/javascript" src="data.json"></script> var mydata = JSON.parse(data); data = '[{"yer" : "Besiktas", "lat" : "41.044161", "lng" : "29.001056"},{"yer" : "Eminönü", "lat" : "41.017513", "lng" : "28.970939"},{"yer" : "Zeyt ...

Are there any substitutes for the CORS Google Chrome extension? What is the best way to effectively send AJAX requests without relying on CORS restrictions?

Hello, I created an Udemy API that retrieves courses using React and axios. The API works fine when the CORS extension is enabled on Chrome, but it fails to fetch data without it. Are there alternative methods to make this work without relying on the exte ...

Triggering server-side code (node.js) by clicking a button in an HTML page created with Jade

I am currently working on developing a web application and have encountered an issue where I need to execute some server-side code when a button is clicked (using the onClick event handler rather than the Submit button). My tech stack includes Node.js, Exp ...

Error: The initial parameter must be a string, Buffer, ArrayBuffer, Array, or Array-like Object. An object type was passed in instead in CryptoJS

In my quest to encrypt and decrypt data in react-native, I embarked on using the crypto node module by incorporating it into my react native project through browserify. While attempting encryption with the code snippet provided below, an error surfaces sta ...

Looking to transform a list into JSON format using JavaScript?

I have a collection that looks like this: <ol class="BasketballPlayers"> <li id="1">Player: LeBron, TotalPoints: 28753, MVP: true</li> <li id="2">Player: Steph, TotalPoints: 17670, MVP: true< ...

Having trouble running the npm run build command with vue-cli for production builds

Anticipated Outcome Executing npm run build should generate the production-ready dist bundle that can be deployed on a specified device. Current Scenario Despite successful local builds, encountering errors when attempting to execute npm run build on an ...

Tips for ensuring session token verification remains intact upon reloading

I am currently in the process of developing a website using the Next.js framework and I am seeking advice on how to prevent the reload effect that occurs when transitioning from the login page back to the main page for just a fraction of a second. Below i ...

The delay in loading HTML content using FOSJsRoutingBundle and Ajax for a specific route parameter (ID)

I'm using FOSjSrouting in my symfony2.7 project. This is the code in my html.twig view: <table> <!--table header code ...etc... --> <tbody> {% for currentData in arrayData %} <tr> <td>{{ currentData. ...

The Angularfire library encountered an issue when trying to access the 'push' property of a null object

I am currently in the process of creating a new object in the database for an assessment. Right now, I have hardcoded it to test its functionality, but ultimately, it will be dynamic based on user input from the view. However, I am encountering an error th ...

Exploring the architecture of Redux-thunk and validating the impact of side effects

I've been using redux-thunk and I'm not entirely sure if my side effects (specifically the showAlertError function) are structured properly. While my jest test setup seems to be fine at first glance, I encountered an error: jest.fn() value mus ...