Can't configure env variables to use cloudinary in react app - reactjs

I'm having problems with cloudinary configurations in my react app. I installed the library and created a cloudinary file like this:
cloudinary.js
import { v2 as cloudinary } from 'cloudinary';
import * as dotenv from 'dotenv';
dotenv.config();
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.CLOUD_API_KEY,
api_secret: process.env.CLOUD_API_SECRET,
secure: true
});
export default cloudinary;
My .env file:
CLOUD_NAME=d*******c
CLOUD_API_KEY=8***********8
CLOUD_API_SECRET=j*************************A
I'm using netlify to deploy. When I'm trying to use cloudinary in other file with import cloudinary from "..."; I'm getting an error like below:
Can someone help? Thanks in advance!

It depends on what you used for setting up the project.
If it's CRA then you have to use REACT_APP_ as the prefix, Reference
If it's Vite then you have to use import.meta.env.VITE_SOME_KEY with VITE_ as the prefix, Reference

Related

Vercel Output Source did not serve Public folder dir

I am using React in this project with Vite.
I have two assets folders inside the Public folder 👇
Images
Icons
When I run the build command vite build the dist includes the images and icons folders from the Puclic and it works fine.
Build Files Image
Here is my vite.config.ts 👇
import { defineConfig } from 'vite'
import react from '#vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
build: {
rollupOptions: {
output: {
assetFileNames: (assetInfo) => {
let extType = assetInfo.name.split('.')[1]
if (/png|jpe?g|svg|gif|tiff|bmp|ico/i.test(extType)) {
extType = 'img'
}
return `assets/${extType}/[name]-[hash][extname]`
},
},
},
},
})
But in Vercel when I depoly the page the Images and icons are not found 404.
In Vercel I can see that the Output Source shows a second assests file that I can't access instead of the images and icons folders.
Vercel Output Source Image
Is this a problem in the build command in Vercel? or do I need to change the build options in vite.config.ts ?
I reached out to Vercel Support and they helped me figure out the problem which was an easy fix.
Vercel is case sensitive on folders names so If you have a Public folder it should be lowercase.
Correct
public âś…
Wrong:
Public ❌
Git might not detect file changes when you rename a folder from uppercase to lower case so I used this git config command to detect the changes 👇
git config core.ignorecase false

How to setup http-proxy-middleware using same endpoint for different api url | React | Axios

I am trying to setup http-proxy-middleware for multiple API URLs with same end point, which is not working.
setupProxy.php
const proxy =require("http-proxy-middleware");
module.exports = function(app)
{
app.use(proxy("rest/V1/orders",{target:"http://example.net/",changeOrigin:true}));
app.use(proxy("rest/V1/orders",{target:"http://example.org/",changeOrigin:true}));
app.use(proxy("rest/V1/orders",{target:"http://example.com/",changeOrigin:true}));
}
use this package for https-proxy-middleware
For setup Create setupProxy.js under src directory
Ref the doc for sample code

React/Next.js recommended way to set constants such as backend API URLs

I am looking through next.js documentation and trying to understand what the suggested approach is for setting URLs that change in different environments. Mostly, I want to ensure that I'm pointing backend URLs correctly in development versus production.
I suppose you can create a constants configuration file, but is there a supported, best practice for this?
Open next.config.js and add publicRuntimeConfig config with your constants:
module.exports = {
publicRuntimeConfig: {
// Will be available on both server and client
yourKey: 'your-value'
},
}
you can call it from another .js file like this
import getConfig from 'next/config'
const { publicRuntimeConfig } = getConfig()
console.log(publicRuntimeConfig.yourKey)
or even call it from view like this
${publicRuntimeConfig.yourKey}
You can configure your next app using next-runtime-dotenv, it allows you to specify serverOnly / clientOnly values using next's runtime config.
Then in some component
import getConfig from 'next/config'
const {
publicRuntimeConfig: {MY_API_URL}, // Available both client and server side
serverRuntimeConfig: {GITHUB_TOKEN} // Only available server side
} = getConfig()
function HomePage() {
// Will display the variable on the server’s console
// Will display undefined into the browser’s console
console.log(GITHUB_TOKEN)
return (
<div>
My API URL is {MY_API_URL}
</div>
)
}
export default HomePage
If you don't need this separation, you can use dotenv lib to load your .env file, and configure Next's env property with it.
// next.config.js
require('dotenv').config()
module.exports = {
env: {
// Reference a variable that was defined in the .env file and make it available at Build Time
TEST_VAR: process.env.TEST_VAR,
},
}
Check this with-dotenv example.

Webpack + `create-react-app` | ProvidePlugin Not Loading React as a Module

* Note: I barely know anything about Webpack.
I want to load the react node module and other modules in Webpack via ProvidePlugin to have global access to them.
I created a create-react-app and ran eject and got access the pre-defined configuration for Webpack create-react-app provides.
I read this post about loading react globally via PluginProvidor and read about PluginProvidor itself in the Webpack docs, where the latter states:
By default, module resolution path is current folder (./**) and node_modules
Based on that, in webpack.config.js, in plugins, I added the following PluginProvidor:
...
plugins: [
new webpack.ProvidePlugin(
{
React: 'react'
}
)
]
...
But it didn't work - in a JSX file when I call React (e.g class MyComponent extends React.Component { ... }) I get an error that says that React isn't defined (and also a React-specfic error that React must be defined in JSX files).
Why doesn't it work? As far as I understand, I'm giving the same identifier I call in my JSX file, and like I mentioned, according to the Webpack docs, to the path of the react module in node_modules - both as required for it to work.
My configuation file: webpack.config.js
It's not a good idea to use ProvidePlugin, and even worse is to eject your CRA.
Instead of ProvidePlugin use globals:
// globals.js
import React from 'react';
window.React = React;
and then import './globals'
import './globals';
// no need import React
import ReactDOM from 'react-dom';
...
For adding plugins to CRA web pack refer to react-app-rewired.
Example of adding a plugin:
/* config-overrides.js */
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = function override(config, env) {
if (!config.plugins) {
config.plugins = [];
}
config.plugins.push(new MonacoWebpackPlugin());
return config;
};
Demo:

how to import aws-sdk to tsx file in react

I used typescript ( tsx ) for react . In upload image task , I used aws-sdk to upload to server s3 . I also installed aws-sdk by npm and typings .
UploadFile.tsx
import * as AWS from 'aws-sdk';
//constant
import DefaultValue from '../../Constants/DefaultValue';
AWS.config.update({
region: DefaultValue.REGION,
credentials: new AWS.Credentials(DefaultValue.ACCESS_KEY_ID, DefaultValue.SECRET_KEY)
});
class UploadFile extends React.Component<any,any> {
s3: any;
constructor() {
super();
this.s3 = new AWS.S3({apiVersion: '2016-11-07'});
}
}
Chrome console error : 'AWS is undefined' .
how can i import AWS ? thanks for help .
You'll need to actually have the aws-sdk package bundled in, or avoid using an import entirely.
If you go the Webpack route and bundle in your dependency, you can read about that here. You'll need to npm install -S aws-sdk and use a loader from TypeScript like ts-loader or awesome-typescript-loader.
If you want to continue using a script tag, then you'll have to write something like the following:
import * as _AWS from "aws-sdk";
declare var AWS: typeof _AWS;
Where the import for _AWS itself will be removed (since you'll have only used it for its types), and then you'll just refer to AWS as you otherwise would.

Resources