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

Exploring the power of tRPC for creating dynamic routes in NextJs

Recently, I embarked on a new project using the complete t3 stack (Nextjs, prisma, tailwind, tRPC), and encountered a minor hiccup. To provide some context, within my database, I have an "artists" table containing fields such as name, email, address, id, ...

Issue Arising from Printing a Custom Instruction in a Schema Generated Document

When dynamically adding a directive, the directive is correctly generated in the output schema. However, it seems to be missing when applied to specific fields. Here is how the directive was created: const limitDirective = new graphql.GraphQLDirective({ na ...

What is the correct method for executing an API request within a div?

I am currently facing a challenge in displaying data in a table sourced from 2 different tables in my database, connected by foreign keys. To retrieve the list of stores, I use the following code snippet: useEffect(()=>{ axios.get("http://localhos ...

The functionality of the AngularJS UI-Router seems to be impaired following the minification of

Hey there, I just developed an app with Angular and implemented ui-router for routing. To reduce the file size, I minified the entire Angular app using gulp-uglify. However, after minifying the app, the child route (nested route) of ui-router is no longer ...

I rely on the handleChange function to update the state value, but unfortunately, it remains unchanged

In my project, I am working on creating multiple responsive forms (form1, form2, and form3) within the same page using framer motion. However, I am facing an issue where the state value is not updating correctly when users fill out the form. Specifically, ...

When I attempt to run several promises simultaneously with Promise.All, I encounter an error

My code contains a series of promises, but they are not being executed as expected. Although the sequence is correct and functional, I have found that I need to utilize Promise.all in order for it to work properly. dataObj[0].pushScreen.map(item => { ...

Maintain the value of `this` using a recursive setImmediate() function

Hey there! I'm working on a node.js app where I need to utilize setImmediate() to recursively call a function while maintaining its context for the next iteration. Let's take a look at an example: var i=3; function myFunc(){ console.log(i ...

Guide on changing the content type of a Response header in a Next.js API route

I am currently working on a Next.js 14 app router and have a requirement to dynamically create an XML file when the API route is called and send it in response. Below is my code snippet: export async function GET(req: NextApiRequest, res: NextApiResponse) ...

suggestions for customizing Angular Material

The guidelines regarding materials specify that: "For any Angular Material component, you are allowed to define custom CSS for the component's host element that impacts its positioning or layout, such as margin, position, top, left, transform, and z- ...

Stagnant variable value after onClick event

After exploring various solutions, none seem to quite fit my needs. I want to update the variable "currentIndex" when a user clicks on an image. Currently, the change occurs within the onClick function but does not affect the outside variable. I am unsur ...

What is the method for getting js_xlsx to include all empty headers while saving the file?

In the midst of developing a Meteor App, I've incorporated the Node.js package known as "js_xlsx" from "SheetJS", produced by "SheetJSDev". This tool enables me to convert an Excel sheet uploaded into JSON on the backend. The intention is to store thi ...

How to extract IDs from a URL in Angular

I'm facing an issue with retrieving the first id from an image URL. Instead of getting the desired id, I am receiving the one after the semicolon ("id" = 1). I have tried various methods but haven't been successful in resolving this issue. Any su ...

Error message: Electron is unable to read properties of undefined, specifically the property 'receive'. Furthermore, the IPC is unable to receive arguments that were sent through an HTML iframe

I am currently working on passing light mode and language data from ipcMain to ipcRenderer via my preload script: Preload.js: const { contextBridge, ipcRenderer } = require("electron"); const ipc = { render: { send: ["mainMenuUpdate& ...

What is the process for changing proxy settings through the command line when using Create React App?

I recently created a React project using Create React App and set up the development server to proxy API requests through the proxy setting in my package.json: ... "proxy": "https://dev-backend.example.com" ... However, I am looking ...

I have encountered an issue where after declaring a JavaScript variable on a specific page, including the JavaScript file does not grant access to it

<script type="text/javascript"> $(document).ready(function () { var SOME_ID= 234; }); </script> <script type="text/javascript" src="<%= HtmlExtension.ScriptFile("~/somefile.js") %>"></script> ...

Understanding intricate JSON structures with JavaScript

Here is the JSON structure that I am working with: var data = [ { "country":"Andorra", "code":"AD", "state":[ { "state_code":"AD1", "state_description":"aaAndorra1" }, { " ...

Error: Unable to access the property 'fontSize' as it is undefined

<!DOCTYPE HTML> <html> <head> <title>Interactive Web Page</title> <link id="mycss" rel="stylesheet" href="mycss.css"> <script> function resizeText(size) { va ...

Storybook files enhanced with ESLint

Can anyone help me with writing a script for the stories extensions as well? Below is what I currently have: "eslint": "eslint '**/{*,*.stories}.{ts,tsx}'", Here's my project structure: src components SomeComponen ...

Deciphering the intricate mechanics behind _.bind

This block of code is an excerpt from the Underscore library, specifically showcasing the implementation of the _.bind function. However, I am struggling to comprehend the purpose behind modifying the prototype of an empty function. var customConstruc ...

I am encountering issues where none of the NPM commands are functioning properly even after updating the

For a few months, I have been using npm without any issues. However, once I installed python/django and created a virtual environment, npm stopped working altogether. An error message similar to the following is displayed: sudo npm install -g react-nativ ...