CORS issue with NextJS fetching Netlify function from localhost

Hi folks,

Just started to dig into Netlify after watching Jason Lengstorf’s FE masters course (great btw). I’ve also just started to learn NextJS. So i’ve spun up a boilerplate site with create next app, deployed it to Netlify with a custom domain and set up a function based on an example from Jason’s tutorial.

Issue is I’m getting a CORS error when I try and fetch from my local dev (localhost:8888).

If I use a relative URL - /.netlify/functions/movies - NextJS throws an error. Next’s fetch util expects an absolute URL.

If i use an absolute URL I get a CORS error -
Access to fetch at ‘https://ecstatic-meitner-f4cfd9.netlify.app/.netlify/functions/movies’ from origin ‘http://localhost:8888’ has been blocked by CORS policy: 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’ve updated my netlify.toml file with
[[headers]]
for = “/"
[headers.values]
Access-Control-Allow-Origin = "

I can’t see where my dist / build directory is to add a _headers file and add “Access-Control-Allow-Origin: *” to it (my .toml file publish directory is “out”)

I’ve tried playing with the headers in the response from my function return.

But I still get the error.

When i access the URL directly in a browser I see the JSON response - https://ecstatic-meitner-f4cfd9.netlify.app/.netlify/functions/movies - and when I deploy to Netlify and hit the custom domain the request works. I only get the error when running locally.

Any idea how I get this to play nicely from localhost? I’ve searched the community posts and haven’t found anything that works. I don’t have much experience debugging this kind of thing so would really appreciate some help. Thanks in advance!

To get it to work with localhost, Next.js does show using micro-cors for example.

Example here

Thanks for the suggestion.

How I fixed it was by using Next’s /pages/api as a proxy for Netlify functions.

I’ll write it out in case it helps anyone else in the future -

My original fetch call was being made from Next’s /pages/index.js inside a custom function. I first created a host variable based on the NODE_ENV value -

const host = process.env.NODE_ENV === ‘development’ ? ‘http://localhost:8888’ : ‘https://ecstatic-meitner-f4cfd9.netlify.app’;

I then created a movies.js file under /pages/api that makes a call to my Netlify function -

const nc = require('next-connect');
const cors = require('cors')
const handler = 
  nc()
      .use(cors())
      .get(async (req, res) => {    
          const host = 'https://ecstatic-meitner-f4cfd9.netlify.app';
          const response = await fetch(`${host}/.netlify/functions/movies`);
          const json = await response.json();
          res.statusCode = 200;
          res.send(json)
      });

This then calls the Netlify function, with an absolute URL so Next doesn’t complain, and I no longer get the CORS access error.

I moved the call from the pages/index.js file into the getStaticProps function, so I could pass the data returned directly into a Next component.

It’s not an ideal solution (short term fix at best), and I don’t want to be making two calls for each data request, but whilst I’m just learning and experimenting it’s enough to keep me progressing. I’ll almost certainly end up settling for one single API approach, most likely Next, as I don’t seem to be able to hit a Netlify function without going through a Next API.

Update:

I’ve realised why I was getting the CORS error and what really fixed my issue above. It wasn’t anything as complex as needing to proxy through Next’s API, it was simply moving the Netlify function fetch call into a getStaticProps function in my pages/index.js file.

getStaticProps is called server side to pre-render the API and not included in the bundles served to the client (according to the docs). Previously i was attempting to fetch in my own custom init function getting called on the client.

Now I can make the fetch call to the (absolute) URL of my Netlify function, within getStaticProps in my pages/index.js page, and everything works perfectly well.

Mystery solved.

edit: I’ve noticed in the control panel Netlify consolidates Nextjs’s API functions with their own functions. Seems like I can make changes to NextJs APIs and hit them locally via localhost whilst dev-ing, but can’t with Netlify functions; they need pushing to access them. So much to learn!