# Netlify Lambda using Express with create-react-app

**URL:** <https://answers.netlify.com/t/netlify-lambda-using-express-with-create-react-app/6865>\
**Category:** Support\
**Tags:** lambda-functions, create-react-app, building\
**Created:** [January 2, 2020, 10:00pm UTC](https://answers.netlify.com/t/netlify-lambda-using-express-with-create-react-app/6865 "2020-01-02T22:00:53Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![MikelMNJ](https://sea1.discourse-cdn.com/netlify/user_avatar/answers.netlify.com/mikelmnj/32/5360_2.png) [@MikelMNJ](https://answers.netlify.com/u/MikelMNJ)\
**Post date:** [January 2, 2020, 10:00pm UTC](https://answers.netlify.com/t/netlify-lambda-using-express-with-create-react-app/6865/1 "2020-01-02T22:00:53Z")

</div>

Hello,

I am trying to get my express app working in production, it is called server.js and located in my functions folder:

```auto
// functions/server.js
const connectDB = require('../config/db');
const express = require('express');
const serverless = require('serverless-http');
const app = express();
const basePath = '/.netlify/functions/server';

// Connect Database
connectDB();

// Init Middleware
app.use(express.json({ extended: false }));

// Define routes
app.use(`${basePath}/auth`, require('./routes/auth'));

module.exports.handler = serverless(app);

```

And here is config/db.js

```auto
// config/db.js
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');

const options = {
  useFindAndModify: false,
  useCreateIndex: true,
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

const connectDB = async () => {
  try {
    await mongoose.connect(db, options);
    console.log('MongoDB connected.');
  } catch(err) {
    console.error(err.message);
    process.exit(1);
  };
};

module.exports = connectDB;

```

This is config/default.json

```auto
{
  "mongoURI": "Value removed for post",
  "jwtSecret": "Value removed for post"
}

```

And finally, a very simplified version of functions/routes/auth.js

```auto
// functions/routes/auth.js
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const auth = require('../middleware/auth');
const User = require('../models/User');
const jwt = require('jsonwebtoken');
const config = require('config');
const { check, validationResult } = require('express-validator');

// @route GET /.netlify/functions/server/auth
// @desc Authenticate provided user credentials
// @access Public
router.get('/', auth, async (req, res) => {
  try {
    const user = await User.findById(req.user.id).select('-password');
    res.json(user);
  } catch(err) {
    res.status(500).send('Server error.');
  }
});

```

This is my /netlify.toml file where the built-functions folder is called ‘lambda’

```auto
[build]
command = "yarn build"
functions = "lambda"
publish = "build"

```

My /jsconfig.json file in the project root:

```auto
{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

```

And start/build/deploy scripts in /package.json

```auto
"scripts": {
    "start": "run-p start:**",
    "start:app": "react-scripts start",
    "start:server": "netlify-lambda serve functions",
    "build": "run-s build:**",
    "build:app": "react-scripts build",
    "build:server": "netlify-lambda build functions",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "deploy": "yarn build && netlify deploy --prod"
  }

```

Edit: Almost forgot if you want a 1:1 to get up and running locally with basic create-react-app, this is src/setupProxy.js

```auto
// src/setupProxy.js
const proxy = require('http-proxy-middleware');

module.exports = app => {
  const basePath = '/.netlify/functions/server';

  app.use(
    basePath,
    proxy({ target: 'http://localhost:9000' })
  );
};

```

I am facing two issues:

1. my /config folder in my local project root does not seem to be available after deployment to Netlify – this path was being used to get my mongoURI and jwtSecret when connecting the db via express – the app was bootstrapped with Create React App, if that helps and is not ejected.

Edit: In production, response status code is 502 with the following:  
`errorMessage: "Configuration property "mongoURI" is not defined"`

1. After manually adding database values directly in the express portion, to temporarily bypass issue 1, the API times out after 10 seconds every time the express app lambda function is invoked in production (/.netlify/functions/server). This does not occur in the local development environment, where everything works as expected.

Edit:In production, response status code is 502 with the following:  
`errorMessage: "2020-01-02T22:27:59.500Z 5d1db543-e1e4-4ade-8f15-fe05c534757b Task timed out after 10.01 seconds"`

Please keep in mind this is Express/mongoose and not using the native lambda event, context, callback.

Edit: Using Node v10.16.3

Any insight will be helpful – thanks.

---

<div class="post-metadata">

**Author:** ![MikelMNJ](https://sea1.discourse-cdn.com/netlify/user_avatar/answers.netlify.com/mikelmnj/32/5360_2.png) [@MikelMNJ](https://answers.netlify.com/u/MikelMNJ)\
**Post date:** [January 3, 2020, 5:56am UTC](https://answers.netlify.com/t/netlify-lambda-using-express-with-create-react-app/6865/2 "2020-01-03T05:56:53Z")

</div>

I was able to solve issue 1:  
`errorMessage: "Configuration property "mongoURI" is not defined"`

by removing the third-party ‘config’ package and folder (including default.json/production.json) and moving config/db.js to functions/connectDB/db.js – then, instead used an environment variable:

```auto
// New location: functions/connectDB/db.js
const mongoose = require('mongoose');

require('dotenv').config();
const { REACT_APP_MONGO_URI: db } = process.env;

const options = {
  useFindAndModify: false,
  useCreateIndex: true,
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

const connectDB = async () => {
  try {
    await mongoose.connect(db, options);
    console.log('MongoDB connected.');
  } catch(err) {
    console.error(err.message);
    process.exit(1);
  };
};

module.exports = connectDB;

```

The same is true for anywhere jwtSecret was needed:

```auto
require('dotenv').config();
const { REACT_APP_JWT_SECRET: jwtSecret } = process.env;

```

This got issue 1 solved locally, but to solve it in production I also had to go to my Netlify site settings \> Build and Deploy \> Environment and added the two environment variables: `REACT_APP_MONGO_URI` and `REACT_APP_JWT_SECRET` with their appropriate values.

Now all that’s left is the lambda function timeout issue in production.

---

<div class="post-metadata">

**Author:** ![MikelMNJ](https://sea1.discourse-cdn.com/netlify/user_avatar/answers.netlify.com/mikelmnj/32/5360_2.png) [@MikelMNJ](https://answers.netlify.com/u/MikelMNJ)\
**Post date:** [January 4, 2020, 12:17am UTC](https://answers.netlify.com/t/netlify-lambda-using-express-with-create-react-app/6865/3 "2020-01-04T00:17:51Z")

</div>

Still unable to figure out why the timeout is occuring – anyone?

---

<div class="post-metadata">

**Author:** ![MikelMNJ](https://sea1.discourse-cdn.com/netlify/user_avatar/answers.netlify.com/mikelmnj/32/5360_2.png) [@MikelMNJ](https://answers.netlify.com/u/MikelMNJ)\
**Post date:** [January 5, 2020, 2:17am UTC](https://answers.netlify.com/t/netlify-lambda-using-express-with-create-react-app/6865/4 "2020-01-05T02:17:21Z")

</div>

Well, I figured out the timeout issue – don’t be a dumb-dumb like me and forget to open up your db for CDN’s to access. Disabling my white list IP in MongoDB Atlas did the trick.

At least the set-up posted above can possibly help future people as it works out of the box – just remember to use your environment variables 😜

---

<div class="post-metadata">

**Author:** ![lestgabo](https://sea1.discourse-cdn.com/netlify/user_avatar/answers.netlify.com/lestgabo/32/16907_2.png) [@lestgabo](https://answers.netlify.com/u/lestgabo)\
**Post date:** [October 11, 2020, 9:14am UTC](https://answers.netlify.com/t/netlify-lambda-using-express-with-create-react-app/6865/5 "2020-10-11T09:14:47Z")

</div>

Update for the proxy. http-proxy-middleware has updated its proxy function and is now called { createProxyMiddleware } and not ‘proxy’

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

module.exports = function (app) {
    app.use(
        createProxyMiddleware('/.netlify/functions', {
            target: 'http://localhost:9000/',
            pathRewrite: {
                '^/\\.netlify/functions': '',
            },
            changeOrigin: true,
        })
    );
};
```

---

<div class="post-metadata">

**Author:** ![simonrumi](https://avatars.discourse-cdn.com/v4/letter/s/96bed5/32.png) [@simonrumi](https://answers.netlify.com/u/simonrumi)\
**Post date:** [January 15, 2022, 5:34pm UTC](https://answers.netlify.com/t/netlify-lambda-using-express-with-create-react-app/6865/6 "2022-01-15T17:34:24Z")

</div>

just wanted to say thanks - reading here about the renaming of “proxy” to “createProxyMiddleware” probably saved me an hour of frustration

---

<div class="post-metadata">

**Author:** ![saad.bahir.1](https://sea1.discourse-cdn.com/netlify/user_avatar/answers.netlify.com/saad.bahir.1/32/23695_2.png) [@saad.bahir.1](https://answers.netlify.com/u/saad.bahir.1)\
**Post date:** [May 3, 2022, 1:36am UTC](https://answers.netlify.com/t/netlify-lambda-using-express-with-create-react-app/6865/7 "2022-05-03T01:36:16Z")

</div>

Just wanted to say thanks for the pathRewrite , because I couldn’t figure out how to override that path!

---

<div class="post-metadata">

**Author:** ![hillary](https://sea1.discourse-cdn.com/netlify/user_avatar/answers.netlify.com/hillary/32/21132_2.png) [@hillary](https://answers.netlify.com/u/hillary)\
**Post date:** [May 3, 2022, 5:43pm UTC](https://answers.netlify.com/t/netlify-lambda-using-express-with-create-react-app/6865/8 "2022-05-03T17:43:17Z")

</div>

Glad this thread got you on the right track-- happy building 🚀
