I'm building React SPA application from ground up using create-react-app and setting up uri address for API server of my SPA. According to official documentation suggested way is to create environment .env files for such kind of needs. I'm using a continuous delivery as part of development workflow. After deployment React SPA application goes in one Docker container and API goes to another. Those containers are deployed in separate servers and I do not know exactly what uri for API will be, so there is no way to create separate .env file for each deployment. Is there any "right way" to provide dynamic configuration for my SPA application so I can easily change environment parameters
API URI examples in SPA
// api.config.js
export const uriToApi1 = process.env.REACT_APP_API1_URI;
export const uriToApi2 = process.env.REACT_APP_API2_URI;
// in App.js
import { uriToApi1, uriToApi2 } from '../components/config/api.config.js';
/* More code */
<DataForm apiDataUri={`${uriToApi1}/BasicService/GetData`} />
/* More code */
<DataForm apiDataUri={`${uriToApi2}/ComplexService/UpdateData`} />
Let's imagine that you build your frontend code in some dist folder that will be packed by Docker in the image. You need to create config folder in your project that also will be added in dist folder (and obvious, will be packed in Docker image). In this folder, you will store some config files with some server-specific data. And you need to load these files when your react application starts.
The flow will be like that:
User opens your app.
Your App shows some loader and fetches config file (e.g. ./config/api-config.json)
Then your app reads this config and continues its work.
You need to setup Docker Volumes in your Docker config file and connect config folder in Docker container with some config folder on your server. Then you will be able to substitute config files in a docker container by files on your server. This will help you to override config on each server.
Related
For business reasons, I have to host my React app on one domain and serve the images/fonts from another domain (ie. S3). Not sure how I can configure the app to do this?
An example, I want to host my React app at:
http://kamilski.com/#/
And then serve my static assets (images and fonts) from:
http://camel.assets.s3.com/***
I don't know how to configure my create-react-app or Webpack to do this. I know that PUBLIC_URL is available but that still forces me to run the React app and assets on the same server.
This isn't too bad - I do a similar thing with a couple of my apps.
First, get the assets you want onto S3 using an S3 bucket.
There's a good youtube video for that here (this is about uploading from your react app, but the AWS setup is similar in some ways): https://www.youtube.com/watch?v=cDj4LPTLR3o
So once you have your aws bucket setup, you'll probably have one called "site_images" for example. At that point you can source those images from S3 like you would any other image:
https://camel.assets.s3.amazonaws.com/images/SOME-IMAGE-ON-AWS
You'd load fonts in a similar way via your css file(s) most likely with something like:
#fontface {
font-family: 'My Awesome Font';
src: url('https://camel.assets.s3.amazonaws.com/fonts/SOME-FONT-ON-AWS')
}
How you do this specifically will depend on your configuration. You'll need to adjust our aws bucket for CORS which can be a bit of a snag. These links should should help you in the right direction though!
https://coderwall.com/p/ub8zug/serving-web-fonts-via-aws-s3-and-cloudfront
Amazon S3 CORS (Cross-Origin Resource Sharing) and Firefox cross-domain font loading
Did you try to use plugins like webpack-s3-plugin
You can define rules for all assets you need.
And of cause you'll have to eject CRA or use something kind of react-app-rewired or rescripts.
I'm deploying my Create React App to a specific path in a larger non-React webapp. For example, I will say the webapp path is www.example.com and the React app is deployed at www.example.com/react/
I have done this by setting the "homepage" property in package.json of the React app to "homepage": "/react", which does properly serve the static files from the /react/ path on my server.
However, when I make API calls from my react app, they go to /react/api/etc instead of /api/etc.
I can configure axios to use a hardcoded base path of www.example.com, but I deploy this to multiple environments with different URLs and need a solution that doesn't rely on a hardcoded value.
I could also write a workaround on the server side, but it would be less clean / mess with my logging and request statistics.
I would love a clean solution if one exists.
what if you used the window.location property in your axios config object:
{
baseURL: `${location.hostname}/api/` // or window.location.hostname
}
I have a serverless application that is using the serverless-offline plugin and create-react-app to load a front-end client, but I'm not sure how I can configure my serverless app to load the index.html page and also the proper link format that I can use within my react app to call the serverless-offline generated routes.
I know that serverless applications typically use a static website hosted on S3 and AWS serverless endpoints within the static links to trigger the handlers, but I'm not sure how I can replicate this in the local environment. Can anyone point me in the right direction?
This is my code structure at the moment:
- frontend (create-react-app)
-- create-react-files
- backend
-- controllers
--- login.js
I then have a proxy set up in my create-react-app config file set to serverless-offline port I configured in my serverless.yml file
I have a web application in React that I needed to implement a contact form. The application is created using create-react-app and the server folder added. For the form I used sendgrid mail. Does the server work on port 4567, how do the app build to work on the domain? It is a one-page application.
Thx, it is important.
When running in production, a React app is simple HTML, CSS, and JavaScript. These files are sent from your server to a client when requested in the same way that requests/responses are handled for any web page. There are a few steps that need to be done before your React app is ready for production
1: Create a Production Build
First you need to create a production build of your app. This process takes all of your separate .js or .jsx files and puts them together into a single minified file, and the same for .css. Then your index.html is updated to include a link to the CSS and script to the JS. This is done so that only three files will need to be sent rather than the 10s or 100s that exist in development.
If you used create-react-app to start your application, you can use the command:
npm run build
to do this. Otherwise, you need to have webpack installed, and then run:
node_modules/.bin/webpack --config webpack.prod.js --mode production
(which you might want to add as a script to package.json).
See React: Optimizing Performance for more.
2. Serve your Application
Now your server should have a route for your application and when it receives a request on that route, the server should respond by sending index.html from your client/build/ directory (where client/ is the directory of the React app).
Here is an example with Node/Express as the server (in app.js):
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname), 'client', 'build', 'index.html');
});
Note that this is just the way to send a static file using Node and can easily be done with any server.
Additional
You mentioned you want to submit forms with your application. If your routes for receiving POST requests match the routes that the forms are on (e.g. form is on /form and server listens for POST on /form) you can just use the default HTML form submission. However this is not a great way to do things when using React because then routing will be controlled by your server rather than by React. Instead you should use some sort of AJAX method to submit the form.
Since your server is now serving your React app (rather than React serving itself as in development), you can just make relative requests and those requests will be made to your server. For example the request (using the fetch API):
const models = await fetch('/api/models');
Will be made to your_host/api/models by default.
in the package.json add
"proxy": "http://localhost:4567"
I'm building a multi tenant app in React (with Webpack setup via base, dev and prod config files), and I'm wondering the best way to create and access per-tenant variables.
When I run my app with:
npm run start tenant1
I am able to access tenant1 in Webpack by using this:
const tenant1 = process.argv[process.argv.length -1];
However, now I'm wondering what is the best way to make that variable globally accessible. My hope is to use that variable to the create a folder structure within the app along the lines of:
/app/${tenant}/img/
/app/${tenant}/css/
/app/${tenant}/components/
Ideally without having to import a variable into every single javascript file.
Any suggestions or links to existing setups would be greatly appreciated.
Update Jan 2019:
I've found a way to achieve this with Create-react-app, not perfect but it works and achieves the following:
Run a React app on port 3000 that works for multiple domains simultaneously.
Forward all requests not handled by React to a back end.
Optionally use SSL in development.
Create-react-app has a proxy option that is very easy to setup. Simply add the following line to your package.json file:
"proxy": "http://localhost:5000"
However, this will not work for multiple domains. There is a more advanced proxy configuration available.
After following these steps, you will be able to control where different requests are sent, but it does not entirely provide the ability to proxy multiple domains - to achieve this:
Create the file .env in the root of your create-react-app project.
Add the following to it:
NODE_PATH=src/
DANGEROUSLY_DISABLE_HOST_CHECK=true
# optionally add this line for SSL in development
HTTPS=true
From the advanced proxy instructions above, you should end up with a file called setupProxy.js in the root of your /src folder - change to the following:
const proxy = require('http-proxy-middleware')
const options = { target: 'https://[::1]:8000', secure: false }
module.exports = function(app) {
app.use(proxy('/api', options))
app.use(proxy('/graphql', options))
}
The magic part is the https://[::1]: 8000, which will forward all domains from the root request to the same back end. This doesn't seem to be well documented anywhere, but I believe it is the IPv6 equivalent of 127.0.0.1.
After this, you can add entries to your hosts file (for example: 127.0.0.1 some-domain.example.com), and in your React app use just the paths (/api or /graphql) and requests should be proxied to the same domain as the browser is running on.
Original answer:
I ended up taking a fairly manual approach to this.
I'm using a react/redux boilerplate, but I've modified the npm scripts like so:
"start:tenant1": "cp -r ./tenants/tenant1 ./app/tenant && cross-env NODE_ENV=development node server",
"start:tenant2": "cp -r ./tenants/tenant2 ./app/tenant && cross-env NODE_ENV=development node server",
Each tenant folder is copied to the app when the development server is run with the relevant command, and files are named the same within each tenant folder (masthead.svg, vars.js, etc) so that imports throughout the app can be static.
Mostly this works because I'm not using a node server in production, a static build folder is generated by the boilerplate.
Hope this helps someone.