mongoose and express not reading from .env file - express

I am having some trouble importing a .env file into my project. I have fallbacks in place so I didn't notice the issue until I was almost done with my project and was having trouble implementing a paypal button that wouldn't load. Now I am testing and I realize that all my env files have not been importing :/
I am new to using express but I think I did everything correctly as far as I can tell (but obviously not lol). I have imported all my dependencies and I am using dotenv:
import express from "express";
import mongoose from "mongoose";
import dotenv from "dotenv";
My code for importing my paypal .env file:
app.get("/api/config/paypal", (req, res) => {
res.send(process.env.PAYPAL_CLIENT_ID || "sb");
});
my .env file (located at the root of my folder structure)
PAYPAL_CLIENT_ID= my key info here without quotes
Where the code is eventually being called
const addPayPalScript = async () => {
}, [dispatch, orderId]); const { data } = await Axios.get('/api/config/paypal');
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = `https://www.paypal.com/sdk/js?client-id=${data}`;
script.async = true;
I am not sure why this configuration is not working. I have tried to move the env file to the same folder as the file that is calling it but this just fails to compile with an error. (I have a frontend and a backend folder) I have tried to move the env file to the root of the backend folder and it fails to compile with the same error message. It seems like the root of the project file is the correct location for the env file and all the information I can find online seems like my code is okay, but I still can not load the link for the paypal button when it is clicked on.
Any help would be greatly appreciated. Thank you!

Here is what you should do :
Instead of import dotenv from "dotenv";
Use :
import {config} from "dotenv";
config()
The only function you need from the dotenv library to read your .env configuration is config, to invoke it i've done config()
Now you can access values by doing : process.env.YOUR_ENV_VARIABLE_NAME

Related

Sveltekit,Supabase and Vercel (problem with Supabase when deploying to Vercel)

I'm trying to set up Sveltekit, Supabase and Vercel.
It works correctly on a local environment (SvelteKit and Supabase), but when I deploy it to Vercel there is a problem with Supabase - "Error: supabaseUrl is required" (I post a screenshot below).
If I don't use Supabase, there are no problems with deploying to Vercel.
Please someone if you have encountered a similar one or have a suggestion to share.
I finally got this to work after doing a couple of things I pieced together from a few sources.
First, I added the the environment variables in Vercel just as the were in the .env file. For example, VITE_SUPABASE_URL and VITE_SUPABASE_ANON_KEY along with their values.
Next, I added some code in the svelte.config.js file. The result of the file looks like this:
import adapter from '#sveltejs/adapter-auto'
/** #type {import('#sveltejs/kit').Config} */
const config = {
kit: {
adapter: adapter(),
vite: {
define: {
'process.env': process.env,
},
},
// hydrate the <div id="svelte"> element in src/app.html
target: '#svelte',
},
}
export default config
I redeployed the project at Vercel, and it worked.
You should add your Supabase URL and Supabase ANON KEY to vercel and stick to the format given below VITE_SUPABASE_URL,VITE_SUPABASE_ANON_KEY if you have initialized according to the supabase guide.
More than adding the configuration to your svelte.config.js file, you should emphasize on adding environment variables to your Vercel environment if you have added this file
// utils/supabase.js
import { createClient } from '#supabase/supabase-js'
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY
export const supabase = createClient(supabaseUrl, supabaseAnonKey)

Vue local config file per App installation

I am new the Vue.js and I am trying first steps with an app. So for understanding the basics, I want a local config file per App installation to customise some needed variables in the code.
So in my main.js I tried the following:
import Vue from 'vue'
import App from './App.vue'
let config;
try {
config = require('../config.json');
} catch (e) {
config = require('../public/config.json');
}
Vue.config.productionTip = false;
Vue.prototype.$localConfig = config;
new Vue({
render: h => h(App)
}).$mount('#app');
This is working, until I build the production version with the dist folder. If I open the config.json in the root of the dist and change a property value, I see always the first defined values from the development env. So is webpack making there some caching? Is this at all the right way of handling such a local config file per App installation?
Maybe someone could give me some tips on this.
Doing config = require('../config.json'); is the same as import config from "../config.json" in a way that it takes the content of your json file at build time, transform it into JS object and make's it part of your app bundle.
You can do what you propose in a comment (include the file in a script tag in your index.html) but that means your app is doing additional request to the server to load the config and by doing so increasing "time to render" (time user have to wait until the page is fully rendered)
Most common way to handle app configuration in Vue/Webpack world is by using Environment Variables - those also "work" at build time tho so you need to build your app separately for each environment
let config
const configPromise =
process.env.NODE_ENV === 'development'
? import('../config.json')
: import('../public/config.json')
configPromise.then(res => {
config = res.default
})

How to use passwords with Hapi/Glue/Compose?

I have a project which configures a Hapi web server via glue and compose.
Excerpt from TypeScript file:
import { compose as glue } from 'glue';
import { Store } from 'confidence';
import config from './config.json';
const manifest = new Store(config).get('/', {
env: process.env.NODE_ENV,
});
const options = {
relativeTo: __dirname,
};
const server = await glue(manifest, options);
The problem now is that all passwords are directly stored in the config.json file.
Does confidence support the injection of passwords, for example from environment variables?
Or do I somehow have to inject them afterwards, for example using nconf?
I thought same and added my small modification to manifest file. You can use external config library. I am using node-config.
Now I can separate my development and production passwords/keys/secrets.
To .gitignore file I added
config/development.json
config/test.json
config/production.json
Local development uses development.json and production uses production.json. This way I don't need to put my secrets to a file and push to the repo.
Here you can find implementation details. It will give you an idea of how this works.

Serving static files from an express/node.js application

Hi I am a newbie and started to learn about node recently. I took an Heroku tutorial on websockets (https://devcenter.heroku.com/articles/node-websockets) and adapted it for a specific project I was working on. In the example code there was a single index.html file with some embedded javascript. I moved this script out to a separate file and referenced it in the HTML. Everything worked fine locally but doesn't work when i deploy to Heroko. I chatted with the very helpful team at Heroku who informed me that my server side code is serving up all files as HTML and I need to change the code. They gave me some pointers and I tried as many things as I could over several days but to no avail. In the end they recommended coming to this forum as a way to solve the problem as it is beyond their scope. The existing code that serves up the index.html file is as follows:
const express = require('express');
const SocketServer = require('ws').Server;
const path = require('path');
const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'index.html');
const server = express()
.use((req, res) => res.sendFile(INDEX) )
.listen(PORT, () => console.log(Listening on ${ PORT }));
At first i edited this to include the line:
app.use(express.static('public'))
but this didn't work. I then amended as follows and it still doesn't work:
const INDEX = path.join(__dirname, 'index.html');
const JS = path.join(__dirname, 'client.js');
const server = express()
.use((req, res) => {
res.sendFile(INDEX);
res.sendFile(JS);
I have looked at other tutorials that work when i run them in isolation but when I try to adapt my above code it simply doesn't work. I would really appreciate if someone out there could point me in the right direction.
BTW this is what Heroku told me:
"To explain a bit further this error Uncaught SyntaxError: Unexpected token < is because the URL for http://thawing-journey-33085.herokuapp.com/client.js isn't serving a javascript file but is instead trying to serve the HTML for the homepage. This suggests you have an issue with the routing in your application which you'll need to review. This is probably because your server.js file doesn't check for any particular URL before sending the index.html file."
Thanks
I serve my static files like this:
// define the folder that will be used for static assets
app.use(Express.static(path.join(__dirname, '../public')));
// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, '../public', 'index.html'));
});
This way i set the static folder in the express.static middleware so i can serve the files. And then i redirect all url request to the index.html
To know more: express static

React native require relative path file

I am trying React Native iOS and I was trying to setup project environments. I create a file called config.js so later I can just
import config from 'env'
to load the variables based on different environments. The following is the config.js file
let configFile = 'dev.js'
if (NODE_ENV === 'production') {
configFile = 'prod.js'
}
export default require('./env/' + configFile)
Somehow this won't work. the error message is:
Requiring unknown module "./env/dev.js". If you are sure the module is there, try restarting the packager or running "npm install"
When I changed my code to the following it would not give me errors. But it is not what I wanted to do.
export default require('./env/dev.js')
So does anyone know why is that?
Firstly, require calls are not dynamic. They are statically analyzed and bundled. So you would want something like this
let prodConfig = require('./env/prod.js');
let devConfig = require('./env/dev.js');
let config;
if (process.env.NODE_ENV === 'production') {
config = prodConfig;
}else {
config = devConfig;
}
export default config;