How to read/pass vercel system enviroment variables to code in Sanity? - javascript

I want to pass the VERCEL_GIT_COMMIT_REF variable to my javascript bundle. I've deployed Sanity in Vercel and it only passes variables with the prefix SANITY_STUDIO_.
So, I've created an environment variable named SANITY_STUDIO_VERCEL_GIT_COMMIT_REF and want to pass VERCEL_GIT_COMMIT_REF into it.
I tried a few ways but it doesn't seem to work!
Here is what I want to achieve:

You can map environment variables by creating a .env.production file.
SANITY_STUDIO_VERCEL_GIT_COMMIT_REF=${VERCEL_GIT_COMMIT}
https://www.sanity.io/docs/studio-environment-variables#f5e9e3158896

Related

React not picking up environment variables (create-react-app)

I'm trying to access the environment variables in my React App, however they aren't registering.
console.log(process.env)
All of my variables are in a file named .env.development.local, and are prefixed with REACT_APP_
REACT_APP_API_KEY_IF=XXXX
REACT_APP_API_KEY_MAPFLIGHT=XXXX
REACT_APP_SESSION_ID=XXXX
What could I be doing wrong here? Thanks
Alright so it looks like I was supposed to restart the server after adding new Variables, that did it.

Understanding .env file and environment variables in React JS

I'm relatively new to web development world and now I'm trying to understand the usage of .env file in React JS. So, I have read multiple articles and watch some explanation videos. However, most of them were focusing on how to use it rather what it actually is. Do I understand correctly that the main benefits of using environment variables are:
1)They make it easier to maintain applications since they all stored in one file .env
2)They are not visible to users and are not shown and uploaded to Git repository
Is it correct and is there anything else I need to consider?
They are useful to store site-wide values and settings that don't belong in state or as declarations (deep) in the source.
Important to know is that, for react to use them, they have to start with REACT_APP_. This is due to the environment is a nodejs one, and nodejs will claim all variables unless they start with REACT_APP_
Environment variables starting with REACT_APP_ are embedded in the app code during build time.
Do not store any secrets (such as private keys) as REACT_APP_ variables in there! That will expose them in the JS build.
In your react app you can access the variables like so:
let value = {process.env.REACT_APP_MYVALUE}
In HTML you can use the variables as such:
<title>%REACT_APP_SITE_NAME%</title>
A good quick read on usage with create-react-app: https://create-react-app.dev/docs/adding-custom-environment-variables
Usage
Environment (.env) variables are used to store sensitive information, or as the name says, environment-focused information (live, development, debugging, etc...)
.env file is also kept inside .gitignore, so it does not get pushed to any repositories.
Keeping track of variables
.env.example is a file which is not kept in .gitignore, but it is needed for other developers to know how and what to put in their .env. It looks something like this:
.env.example:
REACT_APP_STRIPE_KEY=
MY_SECRET_KEY=
THIS=
FOO=
BAR=
Basically an empty example of what would be .env. This then gets copied and filled with real values in a .env file, which is only available for that developer on that computer, and is read locally by the scripts which then know in what mode to start the app, connected to what database, with what password etc.
Create a file in the root folder.Its .env file
REACT_APP_(VARIABLE_NAME)=KEY_HERE
Usage:
when you added a variable in .env file. Restart your app.
console.log( process.env.REACT_APP_(VARIABLE_NAME) )
And your .gitignore file, add the bellow code
.env

Hiding API keys in JS setup

I'm creating a simple UI with an HTML+CSS+JS setup that uses a third-party API requiring a key and I'd like to keep the key in a file that I can gitignore and access from my Javascript file. I'm not going to be deploying this project, I just want to be able to push it to GitHub without temporarily deleting the variable before every commit.
All responses I've found are related to setups with Node.js, React/Webpack, or other server setups, but I don't have a server or transpiler and don't want to add a bunch of cruft and configurations just for this. Is there a way to do that? I tried storing it in a separate JS file and import/export, but either I couldn't get the syntax right or what I was trying needed a transpiler. Every attempt variation resulted in a syntax error or undefined variable.
Key information:
This is project run entirely locally--as in, just opening index.html in my browser--so I don't think I need to worry about the key being exposed in the client.
My setup pretty much just includes index.html, main.js, and style.css.
I want to push the project to GitHub, so I want to store the api key as a variable in a file separate from main.js that I can add to .gitignore but access in main.js.
I'm keeping this as simple as possible without frameworks, etc. Unless it's super simple and lightweight, I don't want to add libraries just to get this working.
Your best bet is to pull whatever secrets you need from the environment itself, either your environment variables or a secrets store.
The specific implementation will depend on what serverless provider you're using, but for example AWS Lambda lets you configure env vars:
https://docs.aws.amazon.com/lambda/latest/dg/env_variables.html
and you can use the Key Management Service or Parameter Store depending on your preference and requirements:
https://aws.amazon.com/blogs/mt/the-right-way-to-store-secrets-using-parameter-store/
Leaving the above in place in case folks find this via looking at the Serverless tag. Updates below based on the updated question.
So, if I understand the updated question correctly, you want to check in all your code to git except the API key, serve the files only on your local file system and have that local copy be able to access the API key.
The simplest way to do this would be to just have another .js file that defines the variable(s) in question like so:
// config.js
var config = { // this should be const instead if you're using ES6 standards
apiKey : '123456789XYZ'
}
Then, in index.html have another script tag that calls that before any scripts that need the config, e.g.:
<script src='./config.js'></script>
<script src='./main.js'></script>
</body>
In main.js you will then be able to reference the variable config for use, and similarly you can .gitignore 'config.js'.
If you use MVC, try to write in php variabel. Than open in script javasript with echo ...

Share randomly generated variable across .js and .ejs files with nodeJS

I am generating a random number inside a javascript file that I need to pass through to an .ejs file. Obivously I can't just reproduce it there because it is random.
I am working with these files: app.js, game.js and game.ejs. I need to use the variable in both game files.
This is the variable I need to be shared
var num = Math.floor(Math.random()*4)
I already tried passing the variable through my app.js to the game.ejs which worked. I can still not work with it in my game.js though.
Any help is appreciated
make this varibale global like
global.num = Math.floor(Math.random()*4)
now use it at any place inside your environment.
Global varibales must be handled with care as it pollutes

How to use .env file variable in .js file other than Keystone.js?

We are using keystone frame work in one of our project and i am trying to use .env file variable to one of my .js file to connect with http site.I have used dotenv and called process.env.xxyz where xxyz is the variable we are using.Please let me know if there is any other method to call variable from .env file.
Reading process.env is the standard way to retrieve environment variables. See the docs.
The dotenv package you mentioned takes what is in your .env file and puts it in process.env. However, no validation is performed, so it is easy to make mistakes.
Instead, try out my envy module which prevents all of the common mistakes you might be making. It checks for missing variables, amongst other things.
If .env files are still giving you trouble:
Make sure you are using the correct variable names.
Make sure there are no typos.
Make sure you are using the proper syntax.
Consider using command line arguments instead. I recommend meow for this. Also see an example of using envy and meow together.
Regarding syntax: depending on which loader you are using (e.g. dotenv vs envy), the syntax in the .env file could have a big impact on how it is parsed. For example, in Bash and other shells (which the files are based on), each and every one of the following examples behaves entirely differently...
MY_VAR=foo $BAR
MY_VAR='foo $BAR'
MY_VAR="foo $BAR"
Also, environment variable names are case sensitive and by convention are all uppercase. This can lead to mistakes in languages where that is uncommon. In the Node.js program reading process.env, sometimes you might forget that the naming conventions for environment variables are different than the rest of the program.
const myVar = process.env.myVar; // wrong
const myVar = process.env.MY_VAR; // correct
Casing is not an issue if you use envy, as it fixes this by normalizing variable names to camelcase before returning them.
const { myVar } = envy(); // correct, no matter how it is in `.env`
Regardless of which loader you use, you will of course need to call its load function before the .env file will be read. This is pretty much impossible to forget with envy() because you use only its direct return value. But if you are using dotenv, you can easily access process.env at the wrong time because it is already available and populated (but not with all the desired properties) before calling dotenv.config().
Another trick that will help with debugging and save time and effort is to make a dedicated module for configuration. Thanks to the require cache, we avoid doing the work multiple times and also avoid relying upon the loader being idempotent.
Put this in a file called env.js.
const envy = require('envy');
module.exports = envy();
Then import it elsewhere.
const env = require('./env');
Now you have something very simple to debug and it should work the same no matter where you import it.
Just add xxyz=HTTPSiteAddress to your .env file. Then you can call the variable anywhere by using process.env.xxyz.
For example:
var request = require("request");
request(process.env.xxyz, function(error, response, body) {
console.log(body);
});
This will work as long as your keystone.js file contains at the top:
require('dotenv').config();

Categories

Resources