Overcoming CORS issues when developing locally with Gatsby + Netlify Lambda

I spent hours trying to figure out how to bypass a CORS error I encountered when I tried to get my first Gatsby + Netlify Lambda functions development setup to work. My Gatsby was running on http://localhost:3000 and netlify-lambda was running on http://localhost:9000

In the end, I found an article on Gatsby’s website which laid out how exactly to make it work without having to deal with custom HTTP headers and all of that.


First install http-proxy-middleware from npm.

$ npm i -D http-proxy-middleware

Go to your gatsby-config.js and add the following:

var proxy = require("http-proxy-middleware")
module.exports = {
  // for avoiding CORS while developing Netlify Functions locally
  // read more: https://www.gatsbyjs.org/docs/api-proxy/#advanced-proxying
  developMiddleware: app => {
    app.use(
      "/.netlify/functions/",
      proxy({
        target: "http://localhost:9000",
        pathRewrite: {
          "/.netlify/functions/": "",
        },
      })
    )
  },
  // ...
}

Let’s say you have a Lambda function at /lambda/test.js

exports.handler = function(event, context, callback) {
  console.log("queryStringParameters", event.queryStringParameters)
  callback(null, {
    // return null to show no errors
    statusCode: 200, // http status code
    body: JSON.stringify({
      msg: "Hello, World!",
    }),
  })
}

Now you can make a request from anywhere in your Gatsby app!

fetch("/.netlify/functions/test")
  .then(response => response.json())
  .then(console.log)

In development mode, /.netlify/functions/test maps to http://localhost:9000/test and in production, it still just works without you having to make any changes! Neat, eh?

Leave a Reply

Your email address will not be published. Required fields are marked *