Svelte framework: environment variables not appearing in svelte app - javascript

I'm trying to use environment variables in my svelte app. I've installed #Rollup/plugin-replace and dotenv. I created a .env file to hold my API_KEY and added the following to plugins in rollup.config.js from this Medium article:
plugins: [
replace({
__myapp: JSON.stringify({
env: {
isProd: production,
API_URL : process.env.API_URL
}
}),
}),
]
and in the svelte components of my app I would access my API key via
const apiUrl = __myapp.env.API_URL
which worked. However, a few days later I was having authentication issues and after some debugging I found that __myapp.env.API_URL was returning undefined by trying to print it to the console.
I then tried changing the replace call to just replace({'API_KEY': process.env.API_KEY}) and console.log(API_KEY) was still displaying undefined. I tested replace by trying to use it replace some variable with some string and it worked so that confirms that rollup is working fine. So, I suspect the problem is in process.env.API_KEY but I'm not sure. What might I be doing wrong with my attempts to access my environment variables?
(Some background: I am using sveltejs/template as a template to build my app)

dotenv won't register your .env vars until you call config, that's why process.env.API_KEY is undefined when you try to access it.
In your rollup.config.js you can do:
import { config as configDotenv } from 'dotenv';
import replace from '#rollup/plugin-replace';
configDotenv();
export default {
input: 'src/main.js',
...
plugins: [
replace({
__myapp: JSON.stringify({
env: {
isProd: production,
API_URL: process.env.API_URL,
},
}),
}),
svelte({ ... })
]
}

Related

Vite HMR doesn't detect changes to components nested under sub folders

In a Vue + Vite project, I have folder structure like this
The problem is vite doesn't detect changes (ctrl+s) in A.vue or B.vue i.e., components nested under NestedFolder in components folder. Everywhere else works fine.
My vite.config.js looks like this,
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue()
],
resolve: {
alias: {
'#': fileURLToPath(new URL('./src', import.meta.url)),
'#public': fileURLToPath(new URL('./public', import.meta.url))
}
},
server: {
proxy: {
'/api': {
target: 'XXX',
changeOrigin: true,
secure: false,
ws: true,
}
}
}
})
I've tried custom HMR functions as per the vite HMR API docs, got it to send full reload using this.
...
plugins: [
vue(),
{
name: 'custom-hmr',
enforce: 'post',
// HMR
handleHotUpdate({ file, server }) {
if (file.endsWith('.vue')) {
console.log('reloading json file...');
server.ws.send({
type: 'reload',
path: '*'
});
}
},
}
], ...
I looked through vite's HMR API docs but couldn't figure out how to send update event to vite when using custom hmr function
Any help/suggestion on how to solve this would be greatly appreciated.
Ok I solved the problem. The problem is not with nested folders.
Vite seems to ignore components that are imported with absolute path.
E.g. Vite doesn't detect changes in components imported as:
import Dropdown from '#/components/GlobalDropdown.vue'
//# resolves to /src
but detects changes in imports that are relative:
import LoadingSpinner from '../LoadingSpinner.vue'
I couldn't find any setting that addresses this. But having relative paths for component imports solved the issue. Is this an issue?
I think issue is that you made a caseSensitive typo, please check that your path is correct, I had similar issue and this was one letter typed in uppercase.

Environment variables not working (Next.JS 9.4.4)

So i'm using the Contentful API to get some content from my account and display it in my Next.Js app (i'm using next 9.4.4). Very basic here. Now to protect my credentials, i'd like to use environment variables (i've never used it before and i'm new to all of this so i'm a little bit losted).
I'm using the following to create the Contentful Client in my index.js file :
const client = require('contentful').createClient({
space: 'MYSPACEID',
accessToken: 'MYACCESSTOKEN',
});
MYSPACEID and MYACCESSTOKEN are hardcoded, so i'd like to put them in an .env file to protect it and don't make it public when deploying on Vercel.
I've created a .env file and filled it like this :
CONTENTFUL_SPACE_ID=MYSPACEID
CONTENTFUL_ACCESS_TOKEN=MYACCESSTOKEN
Of course, MYACCESSTOKEN and MYSPACEID contains the right keys.
Then in my index.js file, i do the following :
const client = require('contentful').createClient({
space: `${process.env.CONTENTFUL_SPACE_ID}`,
accessToken: `${process.env.CONTENTFUL_ACCESS_TOKEN}`,
});
But it doesn't work when i use yarn dev, i get the following console error :
{
sys: { type: 'Error', id: 'NotFound' },
message: 'The resource could not be found.',
requestId: 'c7340a45-a1ef-4171-93de-c606672b65c3'
}
Here is my Homepage and how i retrieve the content from Contentful and pass them as props to my components :
const client = require('contentful').createClient({
space: 'MYSPACEID',
accessToken: 'MYACCESSTOKEN',
});
function Home(props) {
return (
<div>
<Head>
<title>My Page</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main id="page-home">
<Modal />
<NavTwo />
<Hero item={props.myEntries[0]} />
<Footer />
</main>
</div>
);
}
Home.getInitialProps = async () => {
const myEntries = await client.getEntries({
content_type: 'mycontenttype',
});
return {
myEntries: myEntries.items
};
};
export default Home;
Where do you think my error comes from?
Researching about my issue, i've also tried to understand how api works in next.js as i've read it could be better to create api requests in pages/api/ but i don't understand how to get the content and then pass the response into my pages components like i did here..
Any help would be much appreciated!
EDIT :
So i've fixed this by adding my env variables to my next.config.js like so :
const withSass = require('#zeit/next-sass');
module.exports = withSass({
webpack(config, options) {
const rules = [
{
test: /\.scss$/,
use: [{ loader: 'sass-loader' }],
},
];
return {
...config,
module: { ...config.module, rules: [...config.module.rules, ...rules] },
};
},
env: {
CONTENTFUL_SPACE_ID: process.env.CONTENTFUL_SPACE_ID,
CONTENTFUL_ACCESS_TOKEN: process.env.CONTENTFUL_ACCESS_TOKEN,
},
});
if you are using latest version of nextJs ( above 9 )
then follow these steps :
Create a .env.local file in the root of the project.
Add the prefix NEXT_PUBLIC_ to all of your environment variables.
eg: NEXT_PUBLIC_SOMETHING=12345
use them in any JS file like with prefix process.env
eg: process.env.NEXT_PUBLIC_SOMETHING
You can't make this kind of request from the client-side without exposing your API credentials. You have to have a backend.
You can use Next.js /pages/api to make a request to Contentful and then pass it to your front-end.
Just create a .env file, add variables and reference it in your API route as following:
process.env.CONTENTFUL_SPACE_ID
Since Next.js 9.4 you don't need next.config.js for that.
By adding the variables to next.config.js you've exposed the secrets to client-side. Anyone can see these secrets.
New Environment Variables Support
Create a Next.js App with Contentful and Deploy It with Vercel
Blog example using Next.js and Contentful
I recomended to update at nextjs 9.4 and up, use this example:
.env.local
NEXT_PUBLIC_SECRET_KEY=i7z7GeS38r10orTRr1i
and in any part of your code you could use:
.js
const SECRET_KEY = process.env.NEXT_PUBLIC_SECRET_KEY
note that it must be the same name of the key "NEXT_PUBLIC_ SECRET_KEY" and not only "SECRET_KEY"
and when you run it make sure that in the log says
$ next dev
Loaded env from E:\awesome-project\client\.env.local
ready - started server on http://localhost:3000
...
To read more about environment variables see this link
Don't put sensitive things in next.config.js however in my case I have some env variables that aren't sensitive at all and I need them Server Side as well as Client side and then you can do:
// .env file:
VARIABLE_X=XYZ
// next.config.js
module.exports = {
env: {
VARIABLE_X: process.env.VARIABLE_X,
},
}
You have to make a simple change in next.config.js
const nextConfig = {
reactStrictMode: true,
env:{
MYACCESSTOKEN : process.env.MYACCESSTOKEN,
MYSPACEID: process.env.MYSPACEID,
}
}
module.exports = nextConfig
change it like this
Refer docs
You need to add a next.config.js file in your project. Define env variables in that file and those will be available inside your app.
npm i --save dotenv-webpack#2.0.0 // version 3.0.0 has a bug
create .env.development.local file in the root. and add your environment variables here:
AUTH0_COOKIE_SECRET=eirhg32urrroeroro9344u9832789327432894###
NODE_ENV=development
AUTH0_NAMESPACE=https:ilmrerino.auth0.com
create next.config.js in the root of your app.
const Dotenv = require("dotenv-webpack");
module.exports = {
webpack: (config) => {
config.resolve.alias["#"] = path.resolve(__dirname);
config.plugins.push(new Dotenv({ silent: true }));
return config;
},
};
However those env variables are gonna be accessed by the server. if you want to use any of the env variables you have to add one more configuration.
module.exports = {
webpack: (config) => {
config.resolve.alias["#"] = path.resolve(__dirname);
config.plugins.push(new Dotenv({ silent: true }));
return config;
},
env: {
AUTH0_NAMESPACE: process.env.AUTH0_NAMESPACE,
},
};
For me, the solution was simply restarting the local server :)
Gave me a headache and then fixed it on accident.
It did not occur to me that env variables are loaded when the server is starting.

Contentful with Nuxt.JS "Expected parameter accessToken"

I made a page which pulls data from Contentful. The data is pulling correctly, but buttons which use functions from methods don't work. Live updating of variables (for example, using v-model) doesn't work either.
I see this error in the console:
I think this error is the problem. Does anyone know what's wrong? I have no clue how to solve it :(
My contentful.js:
const contentful = require('contentful')
const client = contentful.createClient({
space: process.env.CONTENTFUL_ENV_SPACE_ID,
accessToken: process.env.CONTENTFUL_ENV_ACCESS_TOKEN
})
module.exports = client
Code which pulls data:
export default {
layout: "landing_page",
asyncData() {
return client
.getEntries({
content_type: "landingPage"
})
.then(entries => {
return { contentfulData: entries.items[0].fields };
});
},
computed: {
styles() {
return landingPageCss;
}
},
components: {
priceBox,
contact,
home,
aboutUs,
footerDiv
}
};
The best approach is used dotenv package to that. Set your env keys in .env file.
nuxt.config.js file should contain:
const env = require('dotenv').config()
export default {
mode: 'universal',
...
env: env.parsed,
...
}
Look at this video: https://codecourse.com/watch/using-env-files-with-nuxt
If you use dotenv you need to do following steps:
npm install --save-dev #nuxtjs/dotenv
Then you install it as an module. Note here if you using Nuxt.js older then v2.9 then you ahve to go to nuxt.config.js and put your code into the module section:
...
module: [
'#nuxtjs/dotenv'
]
...
If there is no module section then create one.
If you using newer then v2.9 then you put it into the buildModules
...
buildModules: [
'#nuxtjs/dotenv'
]
...
Your variables that are saved in the .env file are now accessable through context.env or process.env

Setting environment variables in Gatsby

I used this tutorial: https://github.com/gatsbyjs/gatsby/blob/master/docs/docs/environment-variables.md
Steps I followed:
1) install dotenv#4.0.0
2) Create two files in root folder: ".env.development" and ".env.production"
3) "follow their setup instructions" (example on dotenv npm docs)
In gatsby-config.js:
const fs = require('fs');
const dotenv = require('dotenv');
const envConfig =
dotenv.parse(fs.readFileSync(`.env.${process.env.NODE_ENV}`));
for (var k in envConfig) {
process.env[k] = envConfig[k];
}
Unfortunately, when i run gatsby develop, NODE_ENV isn't set yet:
error Could not load gatsby-config
Error: ENOENT: no such file or directory, open 'E:\Front-End Projects\Gatsby\sebhewelt.com\.env.undefined'
It works when I set it manually:
dotenv.parse(fs.readFileSync(`.env.development`));
I need environment variables in gatsby-config because I put sensitive data in this file:
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: envConfig.CONTENTFUL_SPACE_ID,
accessToken: envConfig.CONTENTFUL_ACCESS_TOKEN
}
}
How to make it work?
PS: Additional question - As this made me think, I know I shouldn't put passwords and tokens on github, but as netlify builds from github, is there other safe way?
I had a similar issue, I created 2 files in the root ".env.development" and ".env.production" but was still not able to access the env file variables - it was returning undefined in my gatsby-config.js file.
Got it working by npm installing dotenv and doing this:
1) When running gatsby develop process.env.NODE_ENV was returning undefined, but when running gatsby build it was returning 'production' so I define it here:
let env = process.env.NODE_ENV || 'development';
2) Then I used dotenv but specify the filepath based on the process.env.NODE_ENV
require('dotenv').config({path: `./.env.${env}`});
3) Then you can access your variables for your config:
module.exports = {
siteMetadata: {
title: `Gatsby Default Starter`,
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: `${process.env.CONTENTFUL_ID}`,
accessToken: `${process.env.CONTENTFUL_TOKEN}`,
},
},
],
}
You should only use env files when you're comfortable checking those into git. For passwords/tokens/etc. add them to Netlify or whatever build tool you use through their dashboard.
These you can access in gatsby-config.js & gatsby-node.js via process.env.ENV_VARIABLE.
You can't access environment variables added this way in the browser however. For this you'll need to use .env.development & .env.production.
I really dislike the .env.production file pattern, our build system sets up and uses env variables and having extra build steps to write those into a file is weird. But Gatsby only whitelists GATSBY_ of the env vars, with no obvious way of adding your own.
But doing that isn't so hard, you can do it by adding something like this in the gatsby-node.js file:
exports.onCreateWebpackConfig = ({ actions, getConfig }) => {
const config = getConfig();
// Allow process.env.MY_WHITELIST_PREFIX_* environment variables
const definePlugin = config.plugins.find(p => p.definitions);
for (const [k, v] of Object.entries(process.env)) {
if (k.startsWith("MY_WHITELIST_PREFIX_")) {
definePlugin.definitions[`process.env.${k}`] = JSON.stringify(v);
}
}
actions.replaceWebpackConfig(config);
};
After doing a few searches, I found that we can set environment variables through netlify website, here are the steps:
Under your own netlify console platform, please go to settings
Choose build & deploy tab (can be found on sidebar)
Choose environment sub-tab option
Click edit variables and add/put your credentials in
Done!

Vue & Webpack: Global development and production variables

I'm using vue-cli to build my web app. My app uses an api in a number of places like so:
axios.post(API + '/sign-up', data).then(res => {
// do stuff
});
The API variable is a constant containing the beginning of the address, e.g., https://example.com.
How would I detect whether this is a dev or prod build and set that variable accordingly? For now, I have a script tag in my index.html document and I am manually changing it for dev and prod:
<script>var API = 'https://example.com'</script>
Is there a better way to handle this?
If you're using the vue-cli webpack template, within the config folder you'll see two files: dev.env.js and prod.env.js.
Both files contain an object that is globally available throughout your Vue app:
dev.env.js
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
prod.env.js
module.exports = {
NODE_ENV: '"production"'
}
Note that string values require the nested single and double quotes. You can add your own variables like so:
dev.env.js
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
API: '"http://localhost:8000"'
})
prod.env.js
module.exports = {
NODE_ENV: '"production"',
API: '"https://api.example.com"'
}
Now the variable can be accessed within any Vue method from the process.env object:
process.env.API

Categories

Resources