what is the proper way to do config lookups in react? - reactjs

My React app currently uses my local API when making an axios.get() call with the following url:
http://localhost:3000/users
Instead of hard-coding the url, I need my component to do a lookup against the config file that is currently configured for the current environment. For example, when my API is running on Azure the axios get call should use the following url:
https://my-api.azurewebsites.net/users
What is the proper way to lookup this config value in a React app? For example, should I create some type of config.js file? What is the proper import/code for my component to hook into the config file for lookup?

Don't use dotenv, because this package was designed for server-side app - it injects config variables in the process.env dictionary, but the process global variable only exists in Node apps and is not available in the browser.
There are many other ways to do what you want, perhaps the simplest I can think of is to have a config file that exports values, and the values it exports depends on the environment the scripts runs in:
// config.js
const isProd = location.host === 'my-app.azurewebsites.net'; // or any other check
const devConfig = {
axiosBaseUrl = 'http://localhost:3000'
}
const prodConfig = {
axiosBaseUrl = 'https://my-app.azurewebsites.net'
}
export default isProd ? prodConfig : devConfig
// upon starting your app, before making any axios call
import config from './config';
const http = axios.create({
baseUrl: config.axiosBaseUrl
});
// use as such
http.get('/hello-world');
// locally: makes a call to http://localhost:3000/hello-world
// in production: makes a call to https://my-app.azurewebsites.net/hello-world
You can also have a config file which contents depends on the build environment, but that would be more complex to setup and is highly dependent on your build pipeline and there's no details about it in your question.

You can create a config file or can use environment variables.
For environment variables:
Create .env file in the root directory of your project.
Save your URL as REACT_APP_BASE_URL=http://localhost:3000/
Now you can access your base URL when you are making axios requests like this:
process.env.REACT_APP_BASE_URL

Related

React setupProxy.js for different environments

I am very new to react but my issue is really around strategies for deploying my app to different environments (dev, QA, UAT). My react app makes an api call and I am using a setupProxy.js to define the url for that api, works great locally. I have also built the api and it is hosted separately. My question is how do I change the setupProxy.js so that the url respects the environment it's deployed to. Right now I'm using AzureDevops and Octopus for building and deploying. It seems like everything gets compiled so trying to change this file after is built won't work. Just looking to see what your deployment strategies are.
Here is my setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
const baseUri = 'http://localhost:5000/api';
const proxy = {
target: baseUri + '/UsageRequest/ScreenScrapeErrors',
changeOrigin: true
}
const proxy2 = {
target: 'https://www.stackoverflow.com',
changeOrigin: true,
}
module.exports = function (app) {
app.use(
'/SceenScrapeErrors',
createProxyMiddleware(proxy)
);
app.use(
'/jobs',
createProxyMiddleware(proxy2)
);
};
I would like to modify the baseUri variable as it's getting deployed to the different environments.
This blog post may help you: https://octopus.com/blog/javascript-configuration
You can move your environmental configuration to a JSON configuration file and modify your app to read the values from that value.
Octopus can replace variables in JSON configuration files during deployment using the structured configuration variables feature.

How to server a ".html" at certain URL in a Next.js app?

I have an ".html" file that I need to serve in a certain route in my Next.js app, like this ...
/pages/customr-route-name/my-html-file.html
So if I go to my website and type http://example.com/custom-route-name/my-html-file.html I can see it
How can I do that in Next.js?
This one requires an API route and a URL rewrite to get working. And the nice thing is, you'll be able to use this pattern for other things too (like if you want to generate an RSS feed or a sitemap.xml).
NOTE: You will need to be running Next 9.5 for this to work.
0. Move your HTML file (Optional)
Your file doesn't need to be located in the ./pages dir. Let's put it in ./static instead. Just replace your these route-file placeholders with your real filename later: ./static/<route>/<file>.html
1. Create the API route
Next lets you create API routes similar to how you would in an old-style host like Express. Any name is fine as long as it's in ./pages/api. We'll call it ./pages/api/static/<route>/<file>.js
// import
import fs from 'fs';
// vars
const filename = './static/<route>/<file>.html';
// export
export default async function api(req, res) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.write(await fs.readFileSync(filename, 'utf-8'));
res.end();
}
2. Add a rewrite to next.config.js
In Next, rewrites work similar to their apache counterparts. They map a url location to a Next ./page.
// export
module.exports = {
rewrites: async () => [
{source: '/<route>/<file>', destination: './pages/api/static/<route>/<file>'},
],
};
3. Run it!
You should be able to test this with a regular next dev. Of course, changes to next.config.js require you to manually reboot the dev server.
If you look at the Next docs, you'll see you can use wildcards in both the API routes and these redirects, which might help with the direction you're going.
Update for NextJS Version 11
In your public folder you can create a folder structure patterned after the URL you want.
For example:
public/custom-path-folder-name/file.html
will be served at:
http://localhost:3000/custom-path-folder-name/file.html
For more information see the nextjs docs for static file serving

Load dynamic properties after the reactjs bundle

Below is my code. Here I want to read baseURL dynamically after react bundle the code. Means, I want to keep my production URL or developement URL outside the react js structure.
Example: I create .env or property file outside of my package, from there I need to get this URL dynamically after the bundle.
import live from './../myservice/develop'
export default {
baseURL: "http:localhost:8080/myapp",
.../live
};
Thanks in advance,
Arun
I don't think you can, .env file is for when the app bundles.
You could try:
baseURL: process.env.NODE_ENV === 'production' ? prodURL : localURL
do you really need the fully qualified URL? Can you use a relative URL?

How can create a config file for reactjs apps that can changes after app builded?

I want create a config file for my reactjs app that contains for example my base url for axios actions and i want change this file after build my app instead of change url every time then again build the app
You can't update static config after build, but you can make specifice build config
For example for your axios base url
const BASE_URL = process.env["NODE_ENV"] == 'production' ? 'my.prod.url' : 'localhost:3000'
Hope it can help you !

How Do I Configure REST Urls When Running React With Azure API-Management?

I have a reactjs front end that gets data from a spring boot backend via rest calls.
Running locally the code for this looks like:
axios.defaults.baseURL = 'http://localhost:8080/api';
axios.get('/devices').then((resp) => {
this.setState({devices: resp.data});
}).catch(() => {
console.log('Failed to retrieve device details');
});
When I build the code to deploy with npm run build I still have localhost as the url.
How do I build it so that developing locally it uses localhost but deploying it uses a different url?
Once I am in Azure I will have one front end and multiple back ends that need to be pointed to depending on who is logged in.
How do I configure the API-Management layer to route the calls to the correct back end depending on who is logged in (using AD for auth)?
Since I am using APIM for the routing, what should the baseURL be?
Manage those variables in a config file and load based on the environment.
Local Values
you can hardcode local variable directly in a config file
Production Values
- keep place holders and set them from build pipeline or
- hard code them also
E.g:
config.js
const serverVars = {
authUrl: '#{authUrl}#',
apiUrl: '#{apiUrl}#',
};
const localVars = {
authUrl: 'local_auth_url',
apiUrl: 'local_api_url',
};
export function getConfiguration() {
if (process.env.NODE_ENV === 'production') {
return serverVars;
}
return localVars;
}
when you call apiUrl
import axios from 'axios';
import { getConfiguration } from 'config';
axios.defaults.baseURL = getConfiguration().apiUrl;
One approach can be using environment variable. You can have different url based on the environment variable.
Another way is just removing the domain from base url, but this will work only when your backend and frontend domain & port are identical.

Resources