Navigating through cors in next.js

Currently, I have set up my front end using Netlify and my backend using Heroku with Next.js

For the fetch request on the front end, here is an example:

fetch(`https://backendname.herokuapp.com/data`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({"category":"_main"})
  }).then(...);

In the backend file pages/api/data.js:

export default function handler(req, res) {
    req.body=JSON.parse(req.body);

    res.setHeader("Access-Control-Allow-Origin", "https://frontendname.netlify.app/");
    res.setHeader('Access-Control-Allow-Methods', 'POST');
    res.setHeader(
      'Access-Control-Allow-Headers',
      'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'
    )
    if(req.method!='POST')
     return res.end();

    res.json({...})

}

I have also made changes to my next.config.js:

module.exports = {
  async headers() {
    return [
      {
        // matching all API routes
        source: "/api/:path*",
        headers: [
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "https://frontendname.netlify.app/" },
          { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,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" },
        ]
      }
    ]
  },
  reactStrictMode: true,
}

However, despite these configurations, I am encountering the following error:

Access to fetch at 'https://backendname.herokuapp.com/data' from origin 'https://frontendname.netlify.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

I am striving to resolve this without resorting to third-party packages or solutions mentioned in the like of this question.

Answer №1

Issue

https://frontendname.netlify.app/
is not considered as a valid origin. This mismatch in origins between the request and CORS configuration causes the preflight check to fail.

  • The actual origin you are requesting from is https://frontendname.netlify.app,
  • While the allowed "origin" in your CORS configuration is set to
    https://frontendname.netlify.app/
    ,

This discrepancy results in the absence of the Access-Control-Allow-Origin response header being set.

Furthermore, setting CORS headers in multiple locations can lead to issues and should be avoided.

Resolution

To address this issue, remove the trailing slash in the value specified in the Access-Control-Allow-Origin header and ensure that duplicate CORS headers are not included in the response.

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

A Reference Error has been encountered in the file "bundle.js" located at "@polkadot/extension-dapp"

I attempted to create a basic user interface for smart contracts using polkadot.js within the next.js framework. The UI content is straightforward, calling the Flipper contract that serves as an example contract in substrate. Upon compiling, I encountered ...

Ways to transfer a value between two different card elements

I have designed a component with three div cards side by side using bootstrap. The first card displays a list of products, and my intention is that when a product is clicked, the details should appear in the second card on the same page. However, this fun ...

Adding Labels to Doughnut Charts in React using Chart.js 2.0

Currently, I'm exploring the world of data visualizations using react, react-chartjs-2, and chart.js version 2.2.1. While searching for a solution to my inquiry, I came across a potentially relevant answer on this link (specifically check out the upda ...

The functionality for selecting text in multiple dropdown menus using the .on method is currently limited to the first dropdown

Having trouble selecting an li element from a Bootstrap dropdown and displaying it in the dropdown box? I'm facing an issue where only the text from the first dropdown changes and the event for the second dropdown doesn't work. <div class="dr ...

The issue of duplicated HTML IDs arises when implementing conditional rendering in NextJS components

I am currently utilizing NextJS in my project. One of the components I'm working with is a support component designed to render a single row: const SingleRow = ({ id, label, children }) => { return ( <p id={id}> <span>{label}< ...

Ways to eliminate double slashes from URL in Next Js. Techniques for intercepting and editing a request on the server side using getServerSideProps

Looking to manipulate a server-side request - how can this be accomplished? http://localhost//example///author/admin/// The desired output is: http://localhost/example/author/admin/ In Next Js, how can duplicate slashes in a URL be eliminated and req ...

Is JSON formatting essential for Highcharts? How to divide and preprocess data for creating charts?

Seeking assistance with extracting data from a JSON at the following link: I am attempting to integrate this data into highcharts for visualization. Although I have a functioning chart, I am struggling with properly formatting the JSON mentioned above du ...

Storing the timestamp of when a page is accessed in the database

I am currently working on a PHP website where users can register and access exclusive Powerpoint presentations. The owner has requested that I track the amount of time users spend viewing each presentation, but I am unsure of how to display and record th ...

Utilizing db.system.js Function within the $where Clause

Here is an illustration of a basic function that I have saved: db.system.js.save({_id: "sum", value: function (x, y) { return x + y; }}); However, when attempting to call it within the $where clause, a Reference not exist error occurs. <?php $collec ...

Save a SQL query as a text file using Node.js

I'm having an issue with my code. I am trying to save the results of a SQL query into a text file, but instead of getting the actual results, all I see in the file is the word "object." const fs = require('fs'); const sql = require('mss ...

The Formik form is not being populated with data from the API

While working on a functional component in ReactJS, I created a simple form using Formik. The input fields in my form are supposed to fetch data from an API when the component mounts. To achieve this, I utilized fetch and useEffect. However, after fetching ...

MaterialUI/Next.js digital clock selector

I am attempting to display a digital time picker or duration picker (minutes and seconds only) in my project theme, which utilizes material UI and Next.js. I have implemented the materialUI config for this but it always displays an analog clock instead of ...

Issue with React Google Maps Api: Error occurs while trying to access undefined properties for reading 'emit'

I'm trying to integrate a map using the google-map-react API, but I keep encountering the following error: google_map.js:428 Uncaught TypeError: Cannot read properties of undefined (reading 'emit') at o.r.componentDidUpdate (google_map.js: ...

Get a Blob as a PNG File

Hope you had a wonderful Christmas holiday! Just to clarify, I am new to JS and may make some unconventional attempts in trying to download my Blob in PNG format. I am facing an issue with exporting all the visual content of a DIV in either PDF or image ...

What is the best method for obtaining user data when additional custom data is stored in Cloud Firestore?

Storing the user's information such as email, name, age, phone number, and uid is essential. In the user.model.ts file: export interface User { uid: string, name: string, email: string, phoneNumber: string, age: string } In auth. ...

Aggregate the values of a key in an associative array and organize them by their respective key

I have a table set up like this: <table> <thead> <th>PRODUCT</th> <th>QUANTITY</th> <th>AREA</th> <th>PRICE</th> <th>TOTAL</th> <tr> &l ...

Utilizing jQuery to select an attribute containing a special character

There is a special div with a unique data-id: <div data-id=""> </div> I tried to target this div using jQuery, but it didn't work as expected: jQuery("[data-id='']").text('hello'); Can anyone help me on how to ...

Utilizing a particular Google font site-wide in a Next.js project, restricted to only the default route

My goal is to implement the 'Roboto' font globally in my Next.js project. Below is my main layout file where I attempted to do so following the documentation provided. import type { Metadata } from "next"; import { Roboto } from "n ...

What is the best way to deactivate the first two columns of the header in Vue?

I am attempting to deactivate the draggable function for the first 2 columns. I have tried using options in the draggable plugin. :options="{disabled : 'Subject'}" However, this disables the draggable functionality for all headers. < ...

Is there a way to utilize JavaScript or jQuery to modify the background color of the `Save` and `Cancel` buttons within a SharePoint 2013 edit form?

Is there a way to modify the background color of the Save and Cancel buttons on a SharePoint 2013 edit form using JavaScript or jQuery? ...