Nuxt .env and import a js into a store - vue.js

I have a somewhat large config.js file that I have created to for config type things. I am using a .env to keep secrets and such out of my github. In my .env file I have a variable called environment that I use to determine if I am on local, dev, stage, or prod. In my config.js file I am using that to load my certs and keys, and a bunch of other variables that are dependent on which environment I am on.
In one of my Vuex Store files, when I do the following it works
import config from '#/config'
console.log(process.env.enviorment) // This logs out 'development' which i set in my .env file
const environ = config.developmemt
When I do the following I get 'environ is undefiend', even though I can see 'development' logged out.
import config from '#/config'
console.log(process.env.enviorment) // This logs out 'development' which i set in my .env file
const environ = config[process.env.enviorment]
My VueEx file...
import config from '#/config'
console.log(process.env.enviorment) // <--- This is where it loads undefined at the app.js file which is my store, but loads the value in client.js
console.log(this.app) // <----------- this.app is undefined every time.
const environ = config.developmemt
export const state = () => (
{
environment: eviron
}
)

You can use process.env only during build process. You want to use ENVs in runtime. In nuxt we have built-in ENVs handling:
https://nuxtjs.org/docs/directory-structure/nuxt-config#runtimeconfig
In .env file add your ENVs:
ENVIRONMENT=staging
In nuxt.config.js you can use process.env.ENVIRONMENT, because it will be assigned during build time:
export default {
publicRuntimeConfig: {
environment: process.env.ENVIRONMENT
},
};
Then you can get all your ENVs from publicRuntimeConfig during runtime (in vue and store files):
this.$config.environment
You can check my demo here:
https://codesandbox.io/s/nuxt-envs-hx2cw?file=/pages/index.vue

Related

How to use a CloudFlare Worker Environment Variable in Quasar? (Vue)

Hello & Happy New Year!
I am facing a problem in my Quasar (v1) app in regard to environment variables. I don't want to solve this using dotenv or any other Node package as these are no longer the recommended way to use environment variables in Quasar.
So I have some local environment variables I am setting/using, following the documented best practice on the Quasar official docs:
quasar.conf.js:
build: {
env: {
EXAMPLE: ctx.dev
? JSON.stringify('https://dev.')
: JSON.stringify('https://prod.')
},
This allows me to specify a different endpoint in dev and prod as I would expect, but not ideal for a few obvious reasons.
index.vue:
console.log(process.env.EXAMPLE,'<---API')
I get the expected output of my mock API endpoint. Good.
Now CloudFlare Workers' variables are globally scoped (No process.env object), so once configured in wrangler.toml, it should be possible to simply call them by name:
wrangler.toml:
[vars]
CFEXAMPLE = "example_token"
BUT this does not work (I cannot get my Quasar application to build if I include this as follows). Probably because CFEXAMPLE is not defined in my quasar.conf.js
quasar.conf.js:
build: {
env: {
CFEXAMPLE: CFEXAMPLE
},
I also cannot console.log CFEXAMPLE from my index.vue file either (but I CAN build my app and deploy to CloudFlare OK).
What is the best way to get environment variables working correctly across CloudFlare and localhost please?
Thanks
Ok so thanks to Michal for the hint. In the end I did this:
Firstly create an environment.js.
environment.js:
module.exports = {
dev:{
NODE_ENV: 'development',
PROXY_URL: 'xx',
}
},
prod:{
NODE_ENV: 'production',
PROXY_URL: 'zz',
}
}
}
Next import it and include a function to return the correct environmental var.
quasar.conf.js:
const config = require('./src/boot/environment.js')
module.exports = function(ctx) {
const getEnvVar = p => {
if (ctx.dev) return (config.dev[p])
else return (config.prod[p])
}
...
Finally add environment variables to env:
quasar.conf.js:
env:{
PROXY_URL:JSON.stringify(getEnvVar('PROXY_URL')),
POST_TO:JSON.stringify(getEnvVar('POST_TO')),
FIRESTORE_CREDS:JSON.stringify(getEnvVar('FIRESTORE_CREDS')),
},

How to use dotenv in SvelteKit project?

I'm trying to use dotenv.config() in a SvelteKit project.
I can run npm run build successfully. But when I try to start the server (using node build), it throws Error: Dynamic require of "fs" is not supported.
I tried to comment out the dotenv part in src/routes/test.js and build again, and this time the server started without any errors. (I created the project with npm init svelte#next without typescript, and except for the codes here, nothing else is changed)
How should I use dotenv here to load environment variables at runtime?
svelte.config.js
import node from '#sveltejs/adapter-node';
const config = {
kit: {
adapter: node(),
target: '#svelte'
}
};
export default config;
/src/routes/test.js
import dotenv from 'dotenv';
dotenv.config();
export function get() {
return {
body: {
test: process.env.TEST
}
}
}
.env
TEST=123
No need to explicitly load dotenv.
Vite uses dotenv
https://vitejs.dev/guide/env-and-mode.html#env-files
You can access your variable via import.meta.env.VITE_MY_VAR
Important is that your env variables must be prefixed with VITE_ in order to get them exposed. And if you are already running npm run dev, quit it and start again.
That worked for me.
Since a few weeks SvelteKit has a built-in way to handle environment variables:
https://kit.svelte.dev/docs/modules#$env-dynamic-private
I solved the problem with env-cmd (https://www.npmjs.com/package/env-cmd) by adding env-cmd to the beginning of svelte-kit dev, svelte-kit preview and node build.
Also, use process.env['TEST'] instead of process.env.TEST since process.env.TEST is replaced with ({}) by vite. (https://github.com/vitejs/vite/issues/3176)
This is what I did:
vite has a special config option for server port.
// import adapter from '#sveltejs/adapter-static';
import adapter from '#sveltejs/adapter-node';
import preprocess from 'svelte-preprocess';
import path from 'path';
import dotenv from 'dotenv-flow';
dotenv.config();
/** #type {import('#sveltejs/kit').Config} */
const config = {
// Consult https://github.com/sveltejs/svelte-preprocess
// for more information about preprocessors
preprocess: preprocess(),
kit: {
// hydrate the <div id="svelte"> element in src/app.html
// target: '#svelte',
/*
adapter: adapter({
// default options are shown
pages: 'build',
assets: 'build',
fallback: 'index.html'
}),
*/
adapter: adapter({
out: './build',
precompress: true
}),
vite: {
resolve: {
alias: {
$components: path.resolve('./src/components'),
$stores: path.resolve('./src/stores'),
$api: path.resolve('./src/api')
}
},
build: {
minify: true
},
server: {
port: process.env.PORT || 3000
}
}
}
};
export default config;
I have .env for defaults (dev etc) and .env.local that is ignored in .gitignore for production (keys, etc).
When .env.local is present it uses that port.
edit: this does not work with node-adapter in production. I think we need to declare PORT some other way. it only works with npm run dev

Quasar - get API key from .env into boot files

Get the value of GOOGLE_MAP_API variable in .env file into gmap-vue.js inside boot/ directory
it's working if I use the key right away like this
load: {
key: 'AIzaSyCw9Txxxxxxxxxxxxx',
...
}
but I would like to use the key coming from .env file like this process.env.GOOGLE_MAP_API
quasar.conf.js
module.exports = function (/* ctx */) {
return {
...
boot: [
'gmap-vue'
],
boot/gmap-vue.js
import Vue from "vue";
import * as GmapVue from "gmap-vue";
Vue.use(GmapVue, {
load: {
key: process.env.GOOGLE_MAP_API,
...
}
}
.env
GOOGLE_MAP_API='AIzaSyCw9Txxxxxxxxxxxxx'
it will return an error:
Google Maps JavaScript API warning: InvalidKey
https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key
to summarize if I get the key from process.env it gives error
I've notice that when I access a String value from process.env it always adds double quotes (").
even if there's No double quotes of the string value from .env
so what I did is I use regex;
load: {
key: process.env.GOOGLE_MAP_API.replace(/"/g, ""),
EDIT: if you guys have better answer please give, thanks
For anyone stumbling onto this more recently, there are apparently a couple ways to get environment variables into your app/boot files:
Method 1
Per the latest Quasar docs on environment variables, you can leverage the dotenv library to parse and inject your .env variables into the env object mounted in quasar.config.js:
build: {
env: require('dotenv').config().parsed
}
Now, everything in your .env file will be available in the process.env object everywhere in your app files (boot, components, modules, etc)
Method 2
If you use Vite - I found this explanation on Jason Watmore's Blog. Basically anything you prefix with VITE_ in your .env files is available on the import.meta.env object.

Vue CLI - no .env file found in Vue.js project root

I created a project with Vue CLI 4.1.2, and inside router/index.js, I found:
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
There is no .env file in the project root. So what does process.env.BASE_URL mean? Where is the BASE_URL value set?
process.env is a property that contains the user's environment variables in Node. The .env is an optional file that could be used in Vue CLI projects to create additional environment variables. Note that you could also create .env.production and .env.development files to set variables specific to the current build mode.
BASE_URL is an environment variable automatically set by Vue CLI when running serve or build NPM scripts. Its default value is /, but it can be configured in <projectRoot>/vue.config.js with the baseUrl (deprecated) or publicPath setting:
// vue.config.js
module.exports = {
publicPath: '/my-app/'
}

How to setup environment files for dev, local and prod api urls, flag in NativeScript Vue?

The agenda is to use certain flags and a specific api base url for different modes say dev, local and prod in my NativeScript Vue app.
Just like NativeScript angular has environment.[mode].ts files?
I've tried using .env.[mode] files, by referring to VueJs docs
// https://cli.vuejs.org/guide/mode-and-env.html#environment-variables.com
But this did not favour the scenario.
// Something like this of a config,
module.exports = {
NODE_ENV: "production",
ROOT_API: "some api url"
}
The config should be accessible like this
process.env.ROOT_API throughout the app.
Refer the Pass Environment Variables section in the docs.
You can also provide environmental variables to the Webpack build:
$ tns build android --bundle --env.development --env.property=value
They can be accessed through the env object in the Webpack
configuration:
// webpack.config.js
module.exports = env => {
console.dir(env); // { development: true, property: 'value' }
}
You may update your DefinePlugin something like below,
new webpack.DefinePlugin({
"global.TNS_WEBPACK": "true",
"global.ENV_NAME": JSON.stringify(name),
"global.ENV_PROPERTY": JSON.stringify(env.property),
process: undefined,
}),
Now using global.ENV_PROPERTY anywhere in your project should be replaced by actual value you pass in command line at compile time.
If you are familar with webpack, you may also configure the CopyWebpackPlugin to copy right environment file to your app instead of having variable for each configuration.