Unable to get Next.js server-side environment variable - javascript

I have the following api-helper that sets the base API URI
import getConfig from 'next/config'
// URI for back end
const {publicRuntimeConfig} = getConfig()
const apiUri = publicRuntimeConfig.external_uri;
export {apiUri}
This is my next.config.js (removed other code for brevity)
module.exports = {
publicRuntimeConfig: {
// Will be available on both server and client
external_uri: process.env.NEXT_PUBLIC_TEST_URI,
},
};
On my machine, I've set the environment variable NEXT_PUBLIC_TEST_URI to a value. However, when I look at my API call on the client-side, it is still showing as undefined.
On the other hand, when I populate the environment variables using the .env files in my project folder, everything works as expected.
I understand there may be a need to use getServersideProps in my api-helper but I'm not sure how I can do it in a simple way just to initialize a variable. It would also be good to understand why it works with the .env files but not an actual environment variable on the server.
I need it to work with an actual environment variable on the server as my end objective is to be able to update this variable and restart the node service without needing to rebuild the app.

Related

Unable to access process variable in Vue3JS Vite project

I am creating a vue3 application (created with Vite) that interacts with a smart contract written in Solidity and stored on Ropsten. Therefore I am using web3js to interact with my smart contracts and also web3.storage in order to store some images on IPFS. I have a .env file at the root of my project storing my API key for web3.storage :
VUE_APP_API_TOKEN=VALUE
VITE_API_TOKEN=VALUE
The problem is that apparently web3.storage expects the API token to be stored in process.env and I am unable to access the global process variable from my application. I am always getting an error Uncaught ReferenceError: process is not defined.
I think, this is linked to my usage of Vite instead of pure Vue3.
I tried to export process env in the vite.config.ts file with that code but it didn't work:
export default ({ mode }) => {
process.env = { ...process.env, ...loadEnv(mode, process.cwd(), '') };
console.log(process.env.VITE_API_TOKEN) //Works fine: VALUE is logged
console.log(process.env.VUE_APP_API_TOKEN) //Works fine: VALUE is logged
return defineConfig({
plugins: [vue()]
});
}
How could I access the process variable from my vue files in order to get the values of my environment variable and make web3.storage work?
.env
VITE_WEB3_STORAGE_TOKEN="your_token"
SomeComponent.vue: (or any other file of your app, really):
console.log(import.meta.env.VITE_WEB3_STORAGE_TOKEN) // "your_token"
Note: as specified in vite documentation, only variables prefixed with VITE_ will be exposed:
To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code.
If you're running the build script in CI you will need to make sure that you're creating / populating the relevant .env file before you run the build script.

How can I create environment variables and use them in a react library, without using webpack?

I have tried dotenv and cros-env. And also with mentioning it in this link
https://create-react-app.dev/docs/adding-custom-environment-variables/
However, it doesn't work for me
My .env file
MY_VAR=value
I have this in the file where I want to call it
console.log(process.env)
const { MY_VAR } = process.env
console.log(MY_VAR)
and i get this
As noted here, environment variables for your frontend must begin with REACT_APP. So try REACT_APP_MY_VAR and restart your React server afterwards.

How can I set environment variables on netlify?

I have a netlify react app. which is connected to my github. I'm using emailjs for receiving the messages from whoever reaches to my app.
emailjs deals with three ids 'SERVICE_ID', 'TEMPLATE_ID' and 'USER_ID'. But I don't wanna use them openly in my component js file.
Driver Function
function sendEmail(e) {
e.preventDefault(); //This is important, i'm not sure why, but the email won't send without it
emailjs.sendForm(SERVICE_ID, TEMPLATE_ID, e.target, USER_ID)
.then((result) => {
window.location.reload() //This is if you still want the page to reload (since e.preventDefault() cancelled that behavior)
}, (error) => {
console.log(error.text);
});
}
I think you're referring to environment variables, in order to test that out locally it will vary per the stack you use for creating the app, if you use react create app you can create a .env file in the root of your project and populate the values
REACT_APP_SERVICE_ID ="your_value"
REACT_APP_TEMPLATE_ID ="your_value"
REACT_APP_USER_ID ="your_value"
Don't forget to exclude this file from git, to avoid pushing secrets in your repo. to do that add this to your .gitignore
.env
After that you can call the variables in your code using the process.env like this:
process.env.REACT_APP_SERVICE_ID
Now modify the code:
function sendEmail(e) {
// Your code
emailjs.sendForm(process.env.REACT_APP_SERVICE_ID, process.env.REACT_APP_TEMPLATE_ID, e.target, process.env.REACT_APP_USER_ID)
// your promise
}
To make that work in netlify you would have to add the variable in your netlify project, follow this section to do that: https://docs.netlify.com/configure-builds/environment-variables/#declare-variables
As you noted I added the prefix REACT_APP_, this is because react create app does this:
Note: You must create custom environment variables beginning with
REACT_APP_. Any other variables except NODE_ENV will be ignored to
avoid accidentally exposing a private key on the machine that could
have the same name. Changing any environment variables will require
you to restart the development server if it is running.
If you are using gatsby or nextjs the env variables naming convention might change so please be aware of that.
You can set env variables on netlify. Please have a check the below images.
Check Adding env variables to react app
You can create a .env in your root dir and add your keys, api end points,... inside of it.

Dotenv Webpack - When I change the system environment variables on runtime, the changes is not affected on the app

I build a web app using react, webpack, docker and AWS.
I create a feature which depends on environment variable. So if the environment variable value is true, the feature will be showing on the frontend.
The problem is, when I changed the environment variable on the server (Webpack already done building the app, the app is already deployed and running), my feature is not showing. I guess due to the app cannot read the value changes on system environment variable.
How can I achieve this ? is it possible to do it ?
=====
I use dotenv webpack for managing my environment variables. I already set the systemvars to true to detect all environment variables from the system or .env file.
=====
So why am I doing this, because I dont want to make a Pull Request to push a new value for environment variables. I just want to reserve the environment variables name, and change the value directly from the server if the feature is ready to deployed. And if there is an error, I just need to change the environment variable to something and the feature is down.
You simply cant change environment variable. Evn variables loaded on compile/webpack load time. So once app start u cant change, process.env.
Solution as #jonrsharpe explains. You need to create, some sort of database. It could be memory or file or database. You read data from that. Expose a API, to update the data base.
Express sample:
global.enableFeature = false
app.post("/updateFeatureToggle", (req, res) => {
const enableFeature = req.body.enableFeature
global.enableFeature = enableFeature
res.send({success: "OK"})
})
In another file, read from global.enableFeature. This is in memory-based.

Enviroment variables react

I have a react component which in development will redirect to a localhost url but in production to a different url. In my backend I have the same situation and there i solved it with a package called dotenv. I was wondering how someone would do this in a react front-end.
export default withRouter(function Login(props) {
useEffect(() => {
if(localStorage.getItem('jwt')){
props.history.push('/dashboard');
}
})
const handleLogin = () => {
window.location.href = "http://localhost:8000/auth/google";
}
return (
<LoginView handleLogin={handleLogin}/>
)
})
You can use dotenv to add environment variables to react as well. During app deployment(in the build process) the environment variables must be replaced with the corresponding URLs (as this is the most frequently encountered use case in front-end applications). This can be done while configuring the build process.
Here is an example using Webpack https://medium.com/#trekinbami/using-environment-variables-in-react-6b0a99d83cf5
The whole idea here is to create a file (called just .env) filled with
your environment variables. To prevent people from finding out your
local database password is the same one you use for every single one
of your accounts on the internet , I urge you to add the .env file to
your .gitignore. Your front-end code will refer to the same
environment variable (process.env.API_URL) on both environments
(development/production), but because you defined different values in
your .env files, the compiled values will be different.
I would suggest having a separate .env file for the react app as it should not be accidentally served with the website.
Create React App has a module(built around the node dotenv module) you can use for adding custom environment variables
https://create-react-app.dev/docs/adding-custom-environment-variables/
The environment variables are embedded during the build time. Since
Create React App produces a static HTML/CSS/JS bundle, it can’t
possibly read them at runtime. To read them at runtime, you would need
to load HTML into memory on the server and replace placeholders in
runtime, as described here. Alternatively you can rebuild the app on
the server anytime you change them.
Its depend on how you are using react.
If you are using react-script, you can go will above solution(https://create-react-app.dev/docs/adding-custom-environment-variables/).
But if you are using webpack, try to use DotenvPlugin in place of dotenv module (https://webpack.js.org/plugins/environment-plugin/).
In my opinion, pls don't follow method 1 use in medium link, as env should not be push on git but package.json need to be done.

Categories