Making CORS requests with Express and the Fetch API

If you're migrating to the fetch API, you may have noticed that it works bit differently than the previous gen of networking API's. Particularly, you have a lot more control over what what you are sending and how you are sending it.

But with great power comes great responsibility. If you're accustomed to doing something like the following middleware on your express server:

  
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});
  

You'll notice that, even though this may have worked in the past, that you will run into browser errors.

This is due to the fact that, when you are including cookie or session data, you need to explicitly set the origin.

Fortunately, it's pretty simple to work around this with the following bit of code (use this to replace your current CORS middleware):

  
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});
  

What's happening now is that you're explicitly setting the origin to be equal to where the request is coming from. This is basically the same thing as the * pattern match character, but it avoids the technicality.

Hopefully this was helpful in a pinch and will save you some time.

So let's do this.

Try our no-code surveys that customers actually answer.

Questions or Feedback?

We are always ready to hear from you.