How to use a CloudFlare Worker Environment Variable in Quasar? (Vue) - vue.js

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')),
},

Related

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

Deploy a vue.js app with IIS in sub directory without rebuilding

I want to deploy a vue.js app using IIS. We need to use subfolders and the same application will be present in different subfolders like
/application-dev
/application-qa
/application-production
It is possible to set the path on build time using
module.exports = {
publicPath: '/application-dev'
}
But how can I set this at the time of deployment so that the application can be placed in any subfolder without rebuilding?
i guess this can be a solution
module.exports = {
publicPath: process.env.PATH,
}
and for each environment you usa a different .env example:
.env //local dev
.env.dev //application-dev
.env.qa //application-qa
.env.prod //application-production
therefore for each release there will be a different environment with maybe a different CI for each branch connected to the environment
You could edit the vue.config.js file:
module.exports = {
publicPath: sub-directory
};
or according to NODE_ENV:
module.exports = {
baseUrl: process.env.NODE_ENV === 'production'
? '/production-sub-path/'
: '/'
}
refer this below link for more detail:
https://cli.vuejs.org/config/#baseurl

Nuxt static generated page and axios post

I have a Nuxt project. Everything is OK when I generate a static page.
However, I need to send a POST request to the other server.
I tried to use both a proxy in nuxt.config.js and just direct query, but after deploy to the ngnix eventually, nothing works.
Please help.
UPDATE. Steps to reproduce.
Create Nuxt App including axios and proxy
Configure your proxy for other webservice:
proxy: {
'/api': {
target: 'http://example.com:9000',
pathRewrite: {
'^/api': '/',
},
},
changeOrigin: true,
},
call this service somewhere in the code:
const result = await this.$axios.post('/api/email/subscribe', {email: email})
run "yarn dev" and test the service. It works locally properly.
run 'nuxt generate' and deploy the static code hosting service, for example, hosting.com
run your page which calls the above-mentioned service.
As a result, instead of making POST call to the hosting.com/api/email/subscribe, it calls localhost:3000/api/email/subscribe.
Be sure to install the nuxt versions of axios and proxy in your project #nuxt/axios and #nuxtjs/proxy
after that in your nuxt.config.js add axios as module plus this options for axios and proxy:
modules: [
// Doc: https://axios.nuxtjs.org/usage
'#nuxtjs/axios',
//more modules if you need
],
/*
** Axios module configuration
*/
axios: {
proxy: true,
// See https://github.com/nuxt-community/axios-module#options
},
proxy: {
'/api/': {
target: process.env.AXIOS_SERVER, // I use .env files for the variables
pathRewrite: { '^/api/': '' }, //this should be your bug
},
},
now you can use axios in any part of the code like this
const result = await this.$axios.post('/api/email/subscribe', {email: email})
it will internally resolve to AXIOS_SERVER/email/subscribe without cause cors issues.
EXTRA: test enviroments in local using multiples .env files
you can configure .env for dev and .env.prod for production, after that in local you can use yarn build && yarn start for test your app with your production enviroment. You only need add this at the top of your nuxt.config.js file
const fs = require('fs')
const path = require('path')
if (process.env.NODE_ENV === 'production' && fs.existsSync('.env.prod')) {
require('dotenv').config({ path: path.join(__dirname, `.env.prod`) })
} else {
require('dotenv').config()
}
By definition on the Nuxt docs page what nuxt generate does is: Build the application and generate every route as a HTML file (used for static hosting).
Therefore, using proxy is out of question here. Take note that you path is not even being rewritten.
And probably the result you're looking for is not hosting.com/api/email/subscribe (wit /api), but hosting.com/email/subscribe.
Nevertheless, if you use nginx then I don't think you should use Nuxt's proxy option. Nginx is built just for that so point your API calls there and in nginx config file just declare where it should point further.

How do you remove console.log from a build using the JS Quasar Framework?

I am trying the Quasar Framework (for those not familiar, it's based on Vue) and it's going well. However I've tried running a build (npm run build) and get repeated:
error Unexpected console statement no-console
... so the build fails because it sees console.log(...) and is not happy. My options:
don't use console.log in development. But it's handy.
comment out the eslint rule that presumably enforces that, so letting console.log into production. But that's not ideal for performance/security.
have the build automatically remove any console.log. That's what I'm after.
But how?
I took a look at the build https://quasar.dev/quasar-cli/cli-documentation/build-commands and it mentions using webpack internally and UglifyJS too. Given that, I found this answer for removing console.log in a general Vue/webpack project: https://github.com/vuejs-templates/webpack-simple/issues/21
... but if that's how, where does that go within Quasar since there is no webpack config file? I imagine in the quasar.conf.js file (since I see an 'extendWebpack' line in there - sounds promising). Or is there a better way to do it? How do other people remove console.log in production when using Quasar? Or handle logging without it?
Thanks!
https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-build
quasar.conf.js:
module.exports = function (ctx) {
return {
...
build: {
...
uglifyOptions: {
compress: { drop_console: true }
}
},
}
}
The above will result in configuring terser plugin with the following:
terserOptions: {
compress: {
...
drop_console: true
},
(https://github.com/terser/terser#compress-options)
(you can see the generated config with quasar inspect -c build -p optimization.minimizer)
You still also need to remove the eslint rule to avoid build errors, see https://github.com/quasarframework/quasar/issues/5529
Note:
If you want instead to configure webpack directly use:
quasar.conf.js:
module.exports = function (ctx) {
return {
...
build: {
...
chainWebpack (chain) {
chain.optimization.minimizer('js').tap(args => {
args[0].terserOptions.compress.drop_console = true
return args
})
}
},
}
}
It will do the same as above.
See https://quasar.dev/quasar-cli/cli-documentation/handling-webpack
and https://github.com/neutrinojs/webpack-chain#config-optimization-minimizers-modify-arguments
https://github.com/quasarframework/quasar/blob/dev/app/lib/webpack/create-chain.js#L315
1 Edit package.json in Vue's project what had created it before.
2 Then find "rules": {}.
3 Change to this "rules":{"no-console":0}.
4 if you Vue server in on, off it and run it again. Then the issue will be done.
As an alternative I can suggest using something like loglevel instead of console.log. It's quite handy and allows you to control the output.

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.