Proxy express backend from Create React App in dev and prod

Viewed 190

I'm new to full stacking and have a Create React App hitting a single /api/verify endpoint in an Express backend.

In dev, I proxy the backend in my frontend package.json with "proxy": "localhost:8081"

DevOps needs to deploying this to a GCP nginx env and I need to make the proxy path relative so we don't have to hard code the domain in the proxy.

I have create a .env.development and .env.production but I'm not sure how to use them correctly so a local yarn start proxies localhost:8081 and a production build proxies the real domain.

I have a typical, simple Express server.js but not sure how to tie it all together.

const cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');

require('dotenv').config();

const app = express();

var corsOptions = {
  origin: 'http://localhost:8081',
};

app.use(cors(corsOptions));

app.use(express.json());

app.use(bodyParser.json());

app.disable('x-powered-by');

// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// simple route
app.get('/', (req, res) => {
  res.json({ message: 'Welcome to bezkoder application.' });
});

require('./routes/gallery.routes')(app);

const PORT = process.env.PORT || 8081;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

And my single route:

const { authJwt } = require('../middleware');
const galleryController = require('../controllers/gallery.controller.js');

module.exports = function (app) {
  app.use(function (req, res, next) {
    res.header(
      'Access-Control-Allow-Headers',
      'x-access-token, Origin, Content-Type, Accept',
    );
    next();
  });
  app.get(
    '/api/verify',
    [authJwt.verifyToken],
    galleryController.fanPassGallery,
  );
};
0 Answers
Related