0

I am trying to use netlify lambda functions with create react app, and it is breaking my site.

The repo was made by running npx create-react-app my-app-name, and is the standard create react app boilerplate.

File structure:

root-directory/package.json

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "lambda": "netlify-lambda serve src/lambda"
  },
  "devDependencies": {
    "netlify-lambda": "^2.0.15"
  }

root-directory/netlify.toml:


[build]
  command = "npm build" 
  functions = "lambda" 
  publish = "build"

src/setupProxy.js:


const proxy = require("http-proxy-middleware");

module.exports = function (app) {
  app.use(
    proxy("/.netlify/functions/", {
      target: "http://localhost:9000/",
      pathRewrite: {
        "^/\\.netlify/functions": "",
      },
    })
  );
};


src/lambda/dictionary.js:

exports.handler = (event, context, callback) => {
  callback(null, {
    statusCode: 200,
    body: "hello world",
  });
};

Now, when I try to run npm run start, the app will not load.

The browser displays the error:

This site can’t be reachedlocalhost refused to connect.

When you run npm run lambda and to to the url http://localhost:9000/.netlify/functions/dictionary in the browser, the browser does display "hello, world" as expected.

Also, I am not able to use the netlify cli because when I try to install it, I get permission errors/ access denied, even when I use sudo. So, trying to get this non globally installed way to work.

Maiya
  • 932
  • 2
  • 10
  • 26

2 Answers2

1

I just had the same issue with the same approach with your setupProxy.js. Then I modified the setupProxy.js to below and it worked for me

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
    app.use(createProxyMiddleware('/functions/', { 
        target: 'http://localhost:9000/', 
        pathRewrite: {
            "^\\.netlify/functions": ""
        }
    }));
};
Kevin Chan
  • 148
  • 9
1

I fixed it , please see below - its stripped down all the way to just keeping it as simple as possible with examples for even using node

https://github.com/Kirbyasdf/netlify-react-lambda-node-boilerplate

kirbyasdf
  • 11
  • 1
  • 1
    But how did you fix it? You just included a link. Not everyone is going to follow a link, and the link may also be broken in the future. Please include the relevant fixes here, on Stack Overflow. – kelsny Oct 09 '22 at 02:59