webpack-dev-server develop on https - reactjs

My .NET Core API is exposed over https.
I want to do request to API from my React app running on webpack-dev-server. But webpack-dev-server running on http by default and CORS block any requests.
I reconfigure webpack to force use https (with my *.pfx certificate example),
but then i have 'private connection error' in browser at every refresh (minor problem) and auto-refreshing stops working.
console errors:
> [HMR] Waiting for update signal from WDS...
> app.js:4049 WebSocket connection to 'wss://localhost:8080/sockjs-node/826/sy0x5mcu/websocket' failed: Error in connection establishment: net::ERR_INSECURE_RESPONSE
> [WDS] Hot Module Replacement enabled.
I think that websockets of webpack-dev-server can not establish connection because of https url. But i do not know how to fix this.

Proxy your .NET core api in your webpack dev server config
{
proxy: {
'/api/**': {
target: 'https://localhost:443', // or whichever port it's listening on
secure: false,
changeOrigin: true, // this might not be necessary depending on how restrictive your host is
pathRewrite: {'^/api' : ''}, // rewrite request /api/foo -> https://localhost:443/foo
},
}
}
More docs on proxying with webpack dev server:
https://webpack.js.org/configuration/dev-server/#devserverproxy

Related

How to configure a react capacitor app running on mobile by usb to make http request to sendbird as localhost instead of its IP address?

I have a React webapp that I have converted it to native app using Capacitor. For live reloading, I had to edit capacitor.config.json as follows:
const config: CapacitorConfig = {
//
webDir: 'build',
bundledWebRuntime: false,
server: {
url: 'http://192.XXX.XXX:3000',
cleartext: true
},
};
This works just fine until the app makes a request to sendbird for initialization. I get the error message: 'SendBirdCall needs https connection, except for 'localhost' or '127.0.0.1'. I tried to setup an express https server but failed. Later I created two channels using ngrok - one for the server and one for the app. The sendbird request was successful but the graphql websocket was failing as ngrok does not support websocket links, also tried a tcp link but it failed as well.
I have another app that I created using the Sendbird React Native Quickstart project and I did not need to do any configuration for that. What could be done in order to make sendbird request using localhost from mobile connected via usb while also being able to have a ws connection?
Try to change the url:
const config: CapacitorConfig = {
...
server: {
url: 'http://localhost:3000',
cleartext: true
},
};
And after connecting a physical device execute the following:
cd $ANDROID_HOME/platform-tools
./adb reverse tcp:3000 tcp:3000
Where $ANDROID_HOME is the Android SDK directory.

http proxy middleware is not created proxies in my react app

I am implementing http proxy middleware in to my react app. I want to proxing qa or dev backend services urls from my local .
Example of my dev login url below
https://cors-anywhere.herokuapp.com/https://dev.sju.uk/auth/login
my setupProxy.js
module.exports = function (app) {
app.use('/auth/login' ,createProxyMiddleware({
target: 'https://cors-anywhere.herokuapp.com/https://dev.sju.uk/auth/login',
changeOrigin: true,
})
);
};
I started my app and click the login button and the request got failed with 404 not found error . Not sure why my target is not replacing with my actual http://localhost:9009/auth/login uri to https://cors-anywhere.herokuapp.com/https://dev.sju.uk/auth/login.
Also am not getting proxy created message in my console when we do npm start as well. I am using webpack dev server not react-scripts . If any changes required on webpack side or am i missing anything badly please let me know. I tried small poc it got worked but that is simple without herokuapp things.
It took me some time to understand how the http-proxy-middleware works.
Look at the following diagram from the http-proxy-middleware Docs
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
For simple configurations, any request that your front-end does calling an API get observed by a matching pattern on the path section of the above diagram and overwritten with your target configuration, to be exposed in the header of the request as a different URL. This also help you in the development phase locally to avoid the CORS blocking mechanism of the browsers.
Example:
Let's imagine we need to call from our front-end exposed at http://localhost:3000 to an endpoint located at https://localhost:7005/api/WeatherForecast
This type of calls will be blocked in all browsers by CORS.
So, with the following config, you will be able to bypass the cors problem.
const { createProxyMiddleware } = require('http-proxy-middleware');
const context = [
"/api",
];
module.exports = function (app) {
const webApiProxy = createProxyMiddleware(context[0], {
target: 'https://localhost:7005',
secure: false,
changeOrigin: true,
headers: {
Connection: 'Keep-Alive'
},
logLevel: 'debug'
});
app.use(webApiProxy);
};
With this, any request made from http://localhost:3000 will be intercepted by the proxy-middleware and if it finds a /api in some part of the path will be changed to https://localhost:7005/api and also concatenate the rest of your original path following the /api.
So finally, your front-end will be asking things from http://localhost:3000 but all the request will arrive to https://localhost:7005 as if they were request by https://localhost:7005 and this will fix the Cors problem coz your requesting and responding from the same origin.
I Guess your can fix your problem by writting your config this way:
module.exports = function (app) {
app.use('/auth/login' ,createProxyMiddleware({
target: 'https://dev.sju.uk/auth/login',
changeOrigin: true,
headers: {
Connection: 'Keep-Alive'
},
})
);
};
Bare in mind, this libray not only can help you with the CORS problem but also to perform hundred of things for any request/response like change arguments from the body, add things to the body, add headers, perform operations before the request aka logging what's requested, perform operations on the response aka logging again what has returned, etc, etc.
Hope this will help to resolve your issue!

OAuth responses require a User Pool defined in config

I am unable to connect to userpool which I defined right above: Auth is an amplify Object
Auth.configure({
region: process.env.REACT_APP_AWS_REGION,
userPoolId: process.env.REACT_APP_PROD_UNIFY_COGNITO_USER_POOL_ID,
userPoolWebClientId: process.env.REACT_APP_PROD_UNIFY_COGNITO_CLIENT_ID,
// Cognito Hosted UI configuration
oauth: {
domain: process.env.REACT_APP_PROD_UNIFY_COGNITO_DOMAIN,
scope: ['email', 'openid', 'aws.cognito.signin.user.admin', 'profile'],
redirectSignIn: 'http://localhost:3000',
redirectSignOut: 'http://localhost:3000',
responseType: 'code',
},
});
I get this error in my browser :Unhandled Rejection (Error): OAuth responses require a User Pool defined in config
AuthClass.
What else is there to connecting programmatically to a user pool. I didn't do amplify push,add auth or anything with the amplify cli b/c I don't think it's necessary?
This is most often down to the fact that you have changed your .env file, but not stopped and restarted your local web server.
For instance if you use yarn serve, make sure you stop the process, then update your .env, then yarn serve again.

ReactJS/Next.js: CRA Proxy Does Not Work With Next.js (Attempting To Route API Request To Express server)

I'm currently upgrading a vanilla React app to use Next.js (version 7.0.0). The app was originally built with Create-React-App and utilizes the proxy built in to CRA's server.
In development my React app runs on port 3000 and I have an Express server running on port 5000. Prior to adding Next.js I'd been using a proxy object within the package.json file to route API requests to the server.
API request:
const res = await axios.get('/api/request')
Proxy object in package.json:
"proxy": {
"/api/*": {
"target": "http://localhost:5000"
}
}
This had been working great, but with Next.js I'm now getting an error:
GET http://localhost:3000/api/request 404 (Not Found)
^ This is supposed to be pointing to locahost:5000 (my server)
Does anyone know how I might be able to route API requests from a React/Next.js client to an Express server running on a different port?
OK, so I've figured this out. You can create a Node.js proxy for Express by using http-proxy-middleware
You can then configure the target option to proxy requests to the correct domain:
const proxy = require('http-proxy-middleware')
app.use('/api', proxy({ target: 'http://localhost:5000', changeOrigin: true }));

Webpack dev server with proxy does not handle redirects

I am developing a react application. For development I am using webpack dev server. My backend application is a spring boot. When I make a request and I am not authenticated the backend redirects me to the login page (localhost:8080/login).
My webpack dev server runs on port 3000. All my api call are redirected to the backend using a proxy from the devserver.
devServer: {
historyApiFallback: true,
contentBase: './',
proxy: [{
context: ["/api"],
target: "http://localhost:9090"
}],
changeOrigin: true,
secure: false
When I access a protected resource and I am not authenticated, for example localhost:3000/api/test, I am redirected to localhost:8080/login and I can see 2 request: a 302 request and a 200 request to /login. The problem is that the dev server does not actually do the redirect and does not show the login page. When serving the content from my spring boot application the redirect is done.
Is this a problem related to webpack dev server or is there something wrong in my understanding of the proxy mechanism?

Resources