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

Attempting to send arguments to a jQuery ajax request

After successfully implementing my original ajax call, I decided to create a reusable function for it. This way, I can easily modify the data and URL fields of the ajax call without having to retype everything each time. However, I encountered an issue whe ...

Tips for saving a web page using Selenium Webdriver in JavaScript

Is there a way to programmatically save an entire webpage using Selenium Webdriver JS in Firefox? I have been able to bring up the Save As dialog with the following code: driver.findElement(webdriver.By.tagName('html')).sendKeys(Key.CONTROL + &ap ...

Error message indicating that the preflight request failed access control check in Angular 5 with JWT OAuth integration

After spending hours reading through several posts, I have yet to find a solution to a very common problem. It seems that in order for my JavaScript code to access the resource, the server must include the Access-Control-Allow-Origin header in the response ...

obtainServerSideProps query parameter

Hey there, I'm trying to use NextJS and its getServerSideProps function to send an API Request, but I'm having trouble passing my ID Query Parameter along. The URL for my API is: http://localhost:3001/product/${id} Below is my code: const rout ...

The comparison between 'typeof error' and 'undefined' reveals that the data is

I am encountering an issue with a piece of code that is generating an error, and I have been unable to find a suitable solution in JavaScript. var data = new FormData(); $.each(files, function(key, obj) { data.append(o ...

Determine the central point of the cluster with the most concentrated xy data points

In my project, I have a 200 x 200 square grid where users can vote on the next desired position of an object within this space. Each time a user submits their vote, the XY position is added to an array. Currently, to determine the "winning" position, I ca ...

`html2canvas encountered an issue: Unable to locate a logger instance`

When I use html2canvas to render the same content repeatedly, I encounter an error about 5% of the time. It seems to be sporadic and I'm not sure why it occurs. What could be causing this unpredictable behavior? html2canvas.js:2396 Uncaught (in promi ...

Troubleshooting: Issues with JQuery validation for cross-domain URLs

I'm fairly new to using JQuery and I have a specific requirement which involves validating a link from another domain. If the validation is successful, I need to redirect (open the page in a new window) to that link. Otherwise, I should display an ale ...

Efficiently loading an image in one go

Rendering approximately 3000 records, each row displays: Customer Profile Edit Customer Name, Action 1 John Edit image | Delete image 2 John Edit image | Delete image 3 John Edit image | Delete image 4 John ...

What is the process for clearing the cache of a crawling URL?

Currently, I am operating a crawler that gets triggered through an expressjs call. However, whenever I make the same request again, the crawler runs once more but indicates that all routes have already been completed. I even went to the extent of deleting ...

What is the best way to extract data from a text file that contains multiple data entries separated by pipes (|) using the fs module?

I'm currently utilizing the node.js fs module to read a text file. One thing that I'm wondering is, does the fs module only support reading text files or can it handle other file formats as well? Now, my primary inquiry is if the text file conta ...

Analyzing exif data during the process of uploading a batch of images

My website allows users to upload multiple images simultaneously. I want to check the EXIF rotation tag of each uploaded image in order to manually rotate the images in the browser if needed. I came across a solution for reading the EXIF rotation value of ...

Guide on building a Vue Js input name field with string-variable schema

I have a project using VueJs and I am looking to extract JavaScript variables to create hidden fields. My goal is to set the name of the field based on the index of the variable, following a zig-zag naming schema. For example: <input type="text" nam ...

Safari's Failure to Execute Ajax Requests

My HTML page includes an ajax request that is functioning properly on Firefox, but does not work on Safari. While debugging, I noticed that the readystate is undefined and the status is "". Can anyone suggest why it might not be working on Safari? Javascr ...

transforming array elements into properties of a React component

My text component contains the code below return ( <FormControl variant="outlined" className={classes.formControl}> <Grid container> <TextField id={props.id} label={props.label} d ...

React: The received value for the prop type must be a function, but it was an object

I'm stuck trying to make sense of this error message, and my online search has hit a dead end. Any insights would be greatly appreciated! Attention: Prop type validation failed - expected prop type `leoInfo` to be a function from the `prop-types` pack ...

Determine whether all elements in the array are false using Array.every()

Below is an example of an array: myArray = {firstValue: false, secondValue: false, thirdValue: true, forthValue: false}; The goal is to determine if every value in the array is false. If that condition is met, then perform a specific action. For instance ...

Next.js API Endpoint Call Resulting in Empty Object Returned by Fetch Function

Having an issue with making an API call in Next.js to delete an item from the database. I'm using the "body" field of the fetch to send a string to the API. The fetch call is within a Next.JS page, and the API endpoint is located in the API folder gen ...

Having Difficulty Applying a Background Color to a Class in Bulk

I am working on a unique HTML canvas for pixel art, which is created using a table made up of various divs all sharing the "pixel" class. I want to add a clear button that can reset the entire canvas, but changing the background color of each individual di ...

jQuery Form Validator: requiring double submission

I've been working on implementing the Form Validator using Jquery. After some testing, I noticed that I have to click the submit button twice before the validation kicks in. Why is that? The script is housed in a separate file and included in my proj ...