add custom ca-bundle to next.js for server side calls - reactjs

I have my site domain.com hosted on Vercel. The next.js application talks to a Laravel API deployed at a subdomain.domain.com on AWS for server-side rendering.
I bought a separate SSL certificate for the wildcard domains and added the CAA entries to the DNS for the CA authorities. I see the certificate verified and working fine in the browsers. However, the server-side rendering requests were failing with the following error (local development connecting to the API hosted at subdomain)
event - build page: /user/[profile_id]
wait - compiling...
event - compiled successfully
Error: unable to verify the first certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1321:34)
at TLSSocket.emit (events.js:210:5)
at TLSSocket._finishInit (_tls_wrap.js:794:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:608:12) {
code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
config: {
url: 'https://subdomain.domain.com/api/account/john-doe',
method: 'get',
headers: {
Accept: 'application/json',
Authorization: '',
token: '',
'User-Agent': 'axios/0.21.1'
},
.
.
I came across this package ssl-root-cas, and the issue is fixed (local development) and the pages load fine.
added this snippet to next.config.js
'use strict';
var rootCas = require('ssl-root-cas').create();
rootCas.addFile(__dirname + '/domain.ca-bundle');
// default for all https requests
// (whether using https directly, request, or another module)
require('https').globalAgent.options.ca = rootCas;
However, this doesn't seem to be working when I deploy to my staging site on Vercel.
My guess is Vercel doesn't have the domain.ca-bundle file? The file is added to the git version control, so should exist in the codebase when the build is generated.

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.

What should I use instead of localhost to deploy a React App?

Please, I have this piece of code for a Contact Form in a React APP.
It works fine locally, but after I deploy it doesn't work. I guess I have change the localhost for something else, but for what?
Let's say that my domain is https://www.something.com.
What should I use instead of localhost to deploy my React App?
Error message that I receive if I keep the localhost domain: NetworkError when attempting to fetch resource.
PS.: The website works perfectly as well (locally and after the deploy). What I am trying here is to receive an answer of my fetch method (for my contact form) that it's not working.
fetch('http://localhost:5500/contact', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
body: JSON.stringify(details),
})
Whatever server backend you are running on port 5500 needs to be hosted online too. At the moment you just have your frontend hosted.
Once you have your backend hosted, change your fetch URL to that instead.
have you added the homepage props into the package.json file.?

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!

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 }));

How to allow CORS in Google Cloud Endpoints?

As stated in the January 2017 Endpoints release notes, I tried to update my openapi.yaml file to stop the Extensible Service Proxy (ESP) from blocking cross-origin requests by adding to x-google-endpoints:
swagger: "2.0"
info:
description: "Market scan using technical indicators."
title: "Talib Test"
version: "1.0.0"
host: "YOUR-PROJECT-ID.appspot.com"
x-google-endpoints:
- name: "YOUR-PROJECT-ID.appspot.com"
allowCors: "true"
basePath: "/"
consumes:
- "application/json"
produces:
- "application/json"
schemes:
- "http"
...
I continue to get an error in the browser when trying to make http calls from my angular application. The error is in both developer mode and after I deploy my angular application:
XMLHttpRequest cannot load
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
When i look at Google Cloud logging I see that requestMethod:"OPTIONS" and status:200. The API is a POST method so I'm guessing it's the ESP blocking the request. Also, I have allowed CORS in my python application using FLASK-CORS so it should be working.
My application has two services that are both on Google App Engine. The first is Standard Envrionment. The second, which I am having issues with is Flexible Environment. I am using a dispatch.yaml file and separate openapi.yaml files if that's relevant. Also, the API works on hurl it and postman.
Any help would be awesome!
Most likely your backend application did not handle CORS OPTIONS correctly.
If "allowCors" is true, Endpoint proxy will pass the request to your backend application. Proxy will not add anything to the request. If "allowCors" is false, proxy will return 404.

Resources