PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 3, 2022

[FIXED] How Do You Configure Create React App to Work with Netlify Lambda Functions

 November 03, 2022     create-react-app, lambda, netlify, netlify-function, reactjs     No comments   

Issue

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.


Solution

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": ""
        }
    }));
};


Answered By - Kevin Chan
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing