title: Handling cors with next.js
body: <p>I'm using netlify as my front end and heroku with Next.js as my backend</p>
  <p>on the front end I'm sending a fetch request like this:</p>
  <pre><code>fetch(`https://backendname.herokuapp.com/data`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({&quot;category&quot;:&quot;_main&quot;})
    }).then(...);
  </code></pre>
  <p>and in my <code>pages/api/data.js</code> in the backend:</p>
  <pre><code>export default function handler(req, res) {
      req.body=JSON.parse(req.body);
  
      res.setHeader(&quot;Access-Control-Allow-Origin&quot;, &quot;https://frontendname.netlify.app/&quot;);
      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({...})
  
  }
  </code></pre>
  <p>I even added <a href="https://vercel.com/support/articles/how-to-enable-cors#enabling-cors-in-a-next.js-app" rel="nofollow noreferrer">this</a> to my next.config.js:</p>
  <pre><code>module.exports = {
    async headers() {
      return [
        {
          // matching all API routes
          source: &quot;/api/:path*&quot;,
          headers: [
            { key: &quot;Access-Control-Allow-Credentials&quot;, value: &quot;true&quot; },
            { key: &quot;Access-Control-Allow-Origin&quot;, value: &quot;https://frontendname.netlify.app/&quot; },
            { key: &quot;Access-Control-Allow-Methods&quot;, value: &quot;GET,OPTIONS,PATCH,DELETE,POST,PUT&quot; },
            { key: &quot;Access-Control-Allow-Headers&quot;, value: &quot;X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version&quot; },
          ]
        }
      ]
    },
    reactStrictMode: true,
  }
  </code></pre>
  <p>but I get this error:</p>
  <blockquote>
  <p>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.</p>
  </blockquote>
  <p>I'm trying not to use any third party packages like in <a href="https://stackoverflow.com/questions/65058598/nextjs-cors-issue">this</a> question</p>