Last active
February 16, 2021 10:52
-
-
Save saniaky/3a5e68acc2b1ee69ed49b6a3eaee094a to your computer and use it in GitHub Desktop.
Reverse proxy server for API + create-react-app (CRA)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "test", | |
"version": "0.1.0", | |
"private": true, | |
"scripts": { | |
"app": "concurrently \"node proxy-middleware.js\" \"npm start\"", | |
"start": "react-scripts start", | |
"build": "react-scripts build", | |
"test": "react-scripts test --env=jsdom", | |
"eject": "react-scripts eject" | |
}, | |
"dependencies": { | |
"npm": "^6.4.1", | |
"react": "^16.4.2", | |
"react-dom": "^16.4.2", | |
"react-router": "^4.3.1", | |
"react-router-dom": "^4.3.1", | |
"react-scripts": "1.1.4" | |
}, | |
"devDependencies": { | |
"concurrently": "^4.0.1", | |
"express": "^4.16.3", | |
"http-proxy-middleware": "^0.19.0" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const proxy = require('http-proxy-middleware'); | |
const proxyContexts = { | |
react: { | |
target: 'http://localhost:3000', | |
//changeOrigin: true | |
}, | |
api: { | |
target: 'http://localhost:8080', | |
//changeOrigin: true | |
}, | |
prod: { | |
target: 'https://my-prod.com', | |
changeOrigin: true, | |
onProxyRes: removeSecureCookieFlag | |
} | |
}; | |
/** | |
* Remove "secure" flag from set-cookie header. | |
* Insecure sites (http:) can't set cookies with the "secure" directive anymore (since Chrome 52+ and Firefox 52+). | |
*/ | |
function removeSecureCookieFlag(proxyRes, req, res) { | |
let existingCookies = proxyRes.headers['set-cookie']; | |
let rewrittenCookies = []; | |
if (existingCookies !== undefined) { | |
if (!Array.isArray(existingCookies)) { | |
existingCookies = [existingCookies]; | |
} | |
for (let i = 0; i < existingCookies.length; i++) { | |
rewrittenCookies.push(existingCookies[i].replace(/;\s*?(Secure)/i, '')); | |
} | |
proxyRes.headers['set-cookie'] = rewrittenCookies; | |
} | |
} | |
// https://expressjs.com/en/4x/api.html#app.use | |
const app = express(); | |
// Middleware functions are executed sequentially, therefore the order of middleware inclusion is important. | |
app.use('/api', proxy(proxyContexts.api)); | |
app.use(proxy('ws://localhost:3000')); | |
app.use(proxy(proxyContexts.react)); | |
// Static content if needed | |
// app.use(express.static('build')); | |
app.listen(3100); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment