My application is structured with a frontend server (React) serving static files and a backend server (Express). I have noticed that custom header requests trigger preflight requests, causing latency in my application. My goal is to eliminate these preflight requests for improved performance.
Let's consider this scenario:
frontend: example.web.com
backend: example.api.com
One solution I came across is setting up proxy middleware in the backend server to route requests internally, avoiding the need for requests to bounce from frontend to backend directly.
const proxy = require('http-proxy-middleware');
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
allowedHeaders: "authorization"
}));
let options = {
target: 'http://localhost:5001/',
changeOrigin: true,
logLevel: 'debug',
onError: function onError(err, req, res) {
console.log('Something went wrong with the proxy middleware.', err);
res.end();
}
};
app.use("/", proxy(options), indexRouter);
I was hoping to bypass preflight requests when sending non-"simple" requests. While I knew that using proxy middleware could help achieve this, I needed guidance on how to properly configure it within my Express application.