How to use environment variables in Sveltekit 1.0? - environment-variables

I have an .env file which contains two sensitive items and two non-sensitive. Running Sveltekit 1.0 and using Netlify Serverless functions with a db-helper file which has
require('dotenv').config();
const dbName = process.env.MONGODB_DATABASE;
and similarly gets the other variables. However, this crashes with error "cant find module 'dotenv'!
I tried, with same error ..
const dbName = import.meta.env.MONGODB_DATABASE
I tried process.env['MONGODB_DATABASE'] and import.meta.env['MONGODB_DATABASE']. Failed.
I tried prefixing env vars with VITE using both process.env and import.meta.env with and without [' '] wrapper. Failed.
I read that you dont have to explicitly load dotenv as Vite does this. Tried without. Failed.
Has anyone got a solution to this?

Environment variables should be accessed through these modules:
$env/dynamic/private
$env/dynamic/public
$env/static/private
$env/static/public
Public restricts them to those prefixed with PUBLIC_ (which can be configured).
There is some additional documentation for some adapters regarding the loading of these variables, e.g. for the Node adapter, but there is nothing specific for Netlify.
Looking at the Netlify docs, it looks like you have to use its UI/tools or a Netlify config to load variables rather than using an .env file:
With the Netlify CLI, use env:set to update a site environment variable, env:import to import from an updated .env file, and env:unset to delete a site environment variable and all of its contextual values.

I was using
require('dotenv').config()
which worked locally but gave a "cannot find module dotenv" when deployed (to Netlify). I found that in I used "import" instead of "require" then it worked ..
import dotenv from 'dotenv';
dotenv.config();
So thats a solution. But, H.B. correctly pointed out the new sveltekit way env variables should be used. Thanks for that.
PS. The require/import also fails/works for jsonwebtoken so use import * as jwt from 'jsonwebtoken' instead of const jwt = require('jsonwebtoken')

Related

Why isn't telegraf reading environmental variables?

My goal is to put my telegraf config into source control. To do so, I have a repo in my user's home directory with the appropriate config file which has already been tested and proven working.
I have added the path to the new config file in the "default" environment variables file:
/etc/default/telegraf
like this:
TELEGRAF_CONFIG_PATH="/home/ubuntu/some_repo/telegraf.conf"
... as well as other required variables such as passwords.
However, when I attempt to run
telegraf --test
It says No config file specified, and could not find one in $TELEGRAF_CONFIG_PATH etc.
Further, if I force it by
telegraf --test --config /home/ubuntu/some_repo/telegraf.conf
Then the process fails because it is missing the other required variables.
Questions:
What am I doing wrong?
Is there not also a way of specifying a config directory too (I would like to break my file down into separate input files)?
Perhaps as an alternative to all of this... is there not a way of specifying additional configuration files to be included from within the default /etc/telegraf/telegraf.conf file? (I've been unable to find any mention of this in documentation).
What am I doing wrong?
See what user:group owns /etc/default/telegraf. This file is better used when running telegraf as a service via systemd. Additionally, if you run env do you see the TELEGRAF_CONFIG_PATH variable? What about your other variables? If not, then you probably need to source the file first.
Is there not also a way of specifying a config directory too (I would like to break my file down into separate input files)?
Yes! Take a look at all the options of telegraf with telegraf --help and you will find:
--config-directory <directory> directory containing additional *.conf files
Perhaps as an alternative to all of this... is there not a way of specifying additional configuration files to be included from within the default /etc/telegraf/telegraf.conf file? (I've been unable to find any mention of this in documentation).
That is not the method I would suggest going down. Check out the config directory option above I mentioned.
Ok, after a LOT of trial and error, I figured everything out. For those facing similar issues, here is your shortcut to the answer:
Firstly, remember that when adding variables to the /etc/default/telegraf file, it must effectively be reloaded. So for example using ubuntu systemctl, that requires a restart.
You can verify that the variables have been loaded successfully using this:
$ sudo strings /proc/<pid>/environ
where <pid> is the "Main PID" from the telegraf status output
Secondly, when testing (eg telegraf --test) then (this is the part that is not necessarily intuitive and isn't documented) you will have to ALSO load the same environmental variables into the current user (eg: SET var=value) such that running
$ env
shows the same results as the previous command.
Hint: This is a good method for loading the current env file directly rather than doing it manually.

Reading environment variables from server (not .env file) when using #quasar/quasar-app-extension-dotenv

I’m using #quasar/quasar-app-extension-dotenv for loading environment variables during the development from .env file on my localhost.
In the production I’m hosting the project on Netlify and when I set the environment variables in the Netlify dashboard it is undefined during the program run.
My quasar.extensions.json looks like this:
{
"#quasar/dotenv": {
"env_development": ".env",
"env_production": ".env",
"common_root_object": "none",
"create_env_files": false,
"add_env_to_gitignore": false
}
}
Any ideas how to load variables from server variables?
Thanks
I had the same issue. I found a solution to this, it's not the best but working.
I also used the #quasar/quasar-app-extension-dotenv extension to read the local environment variables from a file. I added this file to gitignore.
After this I wrote a little script which creates a text file with the same name as my local file. It looks like this (I used create-file package to do this):
var createFile = require('create-file')
let contentToWrite = process.argv[2]
createFile('NameOfLocalFile', contentToWrite, function (err) {
if (err) console.log(err)
else console.log('succesfully wrote file')
})
With this script you can pass the environment variable as a parameter.
On netlify I added a build command like this:
(npm run-script writeEnvFile API_KEY=******) && (quasar build || { sleep 120; false; })
So all in all the env file keeps out of github but we pass it's data via the build command. In my case I just need the firebase key to get all my other keys from firebase.
So if you need more keys, you have to extend the script a little bit.
I know this is a messy solution, but it was the only one I found for this issue.

VueJS & Webpack: ENV var unaccessible from built project

I'm working on an app with vuejs frontend and nodejs backend. My frontend makes API https requests to the backend. I've started my projet with vue-cli and webpack.
I need to get the backend API url from env variable (BACKEND_URL).
Since i'm using webpack, I added this line to config/prod.env.js :
module.exports = {
NODE_ENV: '"production"',
-> BACKEND_URL: JSON.stringify(process.env.BACKEND_URL)
}
It works flawlessly in dev mode using webpack-dev-server. I pass the env var throught docker-compose file:
environment:
- BACKEND_URL=https://whatever:3000
But when I run build, I use nginx to serve the static files (but the problem is the same using visual studio code live server extension). I send BACKEND_URL env var the same way as before. The thing is now the process.env.BACKEND_URL is undefined in the app (but defined in the container)!! So I cant make backend http calls :(
I'm struggling finding the problem, please don't be rude with the responses. Thank you
They aren not "translated" during build time, this is what is happening with you. On a node environment, when you ask for process.env it will show all environment variables available in the system, that is true. But a web application does not have access to process.env when it is executing. You need a way to translate them during build time.
To achieve that you have to use DefinePlugin. It translates anything during build time and writes a magical string where this other thing was.
Using you own example:
module.exports = {
NODE_ENV: '"production"',
BACKEND_URL: JSON.stringify(process.env.BACKEND_URL)
}
If you do this during build time, without DefinePlugin, webpack won't know what to do with it, and it is going to be a simple string.
If you use DefinePlugin:
new webpack.DefinePlugin({
"process.env.BACKEND_URL": JSON.stringify(process.env.BACKEND_URL)
});
By doing this, you are allowing webpack to translate this during build time.
Give this a shot: https://www.brandonbarnett.io/blog/2018/05/accessing-environment-variables-from-a-webpack-bundle-in-a-docker-container/
If I'm understanding your problem correctly, you're serving a webpack bundle using nginx, and trying to access an environment variable from that bundle.
Unfortunately, it doesn't quite work that way. Your JS file has no access to the environment since it's a resource that has been delivered to the client. I've proposed a solution that also delivers those env variables alongside the bundle in a separate JS file that gets created on container start.
From VueJS Docs: https://cli.vuejs.org/guide/mode-and-env.html
Using Env Variables in Client-side Code
Only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. You can access them in your application code:
console.log(process.env.VUE_APP_SECRET)
During build, process.env.VUE_APP_SECRET will be replaced by the corresponding value. In the case of VUE_APP_SECRET=secret, it will be replaced by "secret".
So in your case, the following should do the trick. I had the same problem once in my project, which I started with vue/cli and vue create project ...
VUE_APP_BACKEND_URL=https://whatever:3000

React-native run-ios loading environment variables

I want a modern way to manage environment variables for a react native mobile app.
The answer here explains the twelve-factor method style (which I love) which involves installing a babel plugin that transpiles references to
const apiKey = process.env.API_KEY;
to their corresponding values as found in the process's environment
const apiKey = 'my-app-id';
The problem is that in order to run this with a populated environment, I need to set it like
API_KEY=my-app-id react-native run-ios
If I have a .env file with 10-20 environment variables in it, this method becomes unwieldy. The best method I've found so far is to run
env $(cat .env | xargs) react-native run-ios
This is a bit undesirable because developers who want to work on this package have to set up custom shell aliases to do this. This isn't conducive to a good development environment, and also complicates the build and deploy flow for releases.
Is there a way to add a hook to the react-native-cli (or a config file) that populates the process environment first? Like an npm "pre" script, but for react-native.
You can use react-native-config which is a native library and requires a link to work or react-native-dotenv which works just like react-native-config but doesn't require any native link.
It'll work fine with .env files set up, e.g. .env.development with environment variables for process.env.NODE_ENV === 'development'.

How pass/set environment variables into HHVM?

I'm trying to migrate a website from php5-fpm to hhvm.
We use Docker for local dev environments, and we set things like MySQL and Redis details using environment variables that are created using Docker's --link.
With php5-fpm, it was easy to pass these variables into PHP by setting them in www.conf.
With hhvm 3.5.0, I can't seem to find the equivalent. I got close when I found EnvVariables in an example config on this page, but hhvm 3.5.0 now uses INI files for config and I can't seem to find where to set them using these.
Any ideas?
Thanks.
Turns out they were there all along in $_ENV instead of $_SERVER. Must be fastcgi_params.

Resources