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.

2 Answers 2

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": ""
        }
    }));
};
Sign up to request clarification or add additional context in comments.

1 Comment

I haven't been able to check this yet, but I'll just mark it as accepted.
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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.