Npm configure axios - javascript

How I can set baseUrl for axios using npm param?
I would like to write command like this npm run build --baseUrl={url address} and in axios config set baseURL param to param from command.
It is possible ?

I don't think it is possible if you call that --baseUrl like that, as if you do it like that, you're going to have to define --baseUrl for npm start and other scripts, and you'll quickly end up with a spaghetti code.
I humbly suggest a way to mitigate this issue:
Create an .env file that is filled with your environment variables for development. Add this to .gitignore and don't push this into your production server. This file is not used for production.
Add a new BASE_URL variable, like:
BASE_URL=http://YOUR_API_LOCATION/
Use libraries like dotenv (install by npm i dotenv) so you can read .env files.
Create a new utility for axios, let's say:
// client.js
const axios = require('axios');
const dotenv = require('dotenv');
// get all environment variables here.
dotenv.config({ path: '.env' });
// create a new axios instance with the base url from your '.env' file.
const axiosInstance = axios.create({
baseURL: process.env.BASE_URL,
/* other custom settings */
});
module.exports = axiosInstance;
You can reuse your axiosInstance like this:
// request.js
const axiosCustomClient = require('./client');
axiosCustomClient.get('relative/path/to/your/api');

Related

How to load environment variables from .env file using Vite

I want to load environment variables from the .env file using Vite
I used the import.meta.env object as mentioned in Docs
.env file:
TEST_VAR=123F
when trying to access this variable via the import.meta.env -> import.meta.env.TEST_VAR it returns undefined.
so, how can I access them?
According to the docs, you need to prefix your variables with VITE_:
To prevent accidentally leaking env variables to the client, only
variables prefixed with VITE_ are exposed to your Vite-processed code.
If you are trying to access env vars outside your app source code (such as inside vite.config.js), then you have to use loadEnv():
import { defineConfig, loadEnv } from 'vite';
export default ({ mode }) => {
// Load app-level env vars to node-level env vars.
process.env = {...process.env, ...loadEnv(mode, process.cwd())};
return defineConfig({
// To access env vars here use process.env.TEST_VAR
});
}
For svelteKit
// vite.config.js
import { sveltekit } from '#sveltejs/kit/vite';
import { defineConfig, loadEnv } from 'vite';
/** #type {import('vite').UserConfig} */
export default ({ mode }) => {
// Extends 'process.env.*' with VITE_*-variables from '.env.(mode=production|development)'
process.env = {...process.env, ...loadEnv(mode, process.cwd())};
return defineConfig({
plugins: [sveltekit()]
});
};
if you want to access your env variable TEST_VAR you should prefix it with VITE_
try something like
VITE_TEST_VAR=123f
you can access it with
import.meta.env.VITE_TEST_VAR
Here are three mistakes/gotchas that tripped me up.
Ensure the .env files are in the root, not the src directory. The filename .env and/or .env.development will work when running locally.
Restart the local web server for the variables to appear: npm run dev
Prefix the variables with VITE_ (as already mentioned by Mahmoud and Wonkledge)
Another solution that worked for me is to manually call dotenv.config() inside the vite.config.js. That will load variables from .env (all of them!) into process.env:
import { defineConfig } from 'vite'
import dotenv from 'dotenv'
dotenv.config() // load env vars from .env
export default defineConfig({
define: {
__VALUE__: process.env.VALUE
},
//....
}
where .env file could be:
VALUE='My env var value'
As stated in docs, you can change the prefix by mdoify envPrefix.
Env variables starting with envPrefix will be exposed to your client source code via import.meta.env.
So changing it to TEST_ will also work.
export default defineConfig({
...
envPrefix: 'TEST_',
...
})
You can change this option whatever you want except for empty string('').
envPrefix should not be set as '', which will expose all your env variables and cause unexpected leaking of sensitive information. Vite will throw an error when detecting ''.
So overriding the dotenv config directly to remove prefix completely could be an inappropriate action as all fields written in env would send directly into the client.
I had the same issue and solved it by running
pnpm add dot-env
pnpm add -S dotenv-webpack.
Lastly I made sure that I added VITE_ before the name I had for my environment variable, that is from MAP_API_KEY to VITE_MAP_API_KEY.

Environment variables in gatsby-browser.js

I'm trying to make a Keycloak integration with Gatsby.
I'd love to use environment variables for the Keycloak configuration so that I can properly containerize the application. I'm facing an issue about gatsby-browser.js that doesn't get environment variables.
Here's my gatsby-browser.js:
import React from 'react'
import { node } from 'prop-types'
import Keycloak from 'keycloak-js'
import { KeycloakProvider } from '#react-keycloak/web'
import { Spinner } from 'design-react-kit'
require('dotenv').config({
path: `.env.development`
})
const keycloak = new Keycloak({
realm: process.env.KEYCLOAK_REALM,
url: process.env.KEYCLOAK_AUTH_URL,
clientId: process.env.KEYCLOAK_AUTH_CLIENT_ID
})
const Loading = () => {
return (
<div className="container">
<Spinner
active
double
small={false}
tag="span"
/>
</div>
)
}
const wrapRootElement = ({ element }) => {
return (
<KeycloakProvider
keycloak={keycloak}
initConfig={{
promiseType: 'native',
onLoad: 'check-sso',
silentCheckSsoRedirectUri:
window.location.origin + '/silent-check-sso.xhtml'
}}
LoadingComponent={<Loading />}
>
{element}
</KeycloakProvider>
)
}
wrapRootElement.propTypes = {
element: node
}
const _wrapRootElement = wrapRootElement
export { _wrapRootElement as wrapRootElement }
When I launch gatsby develop I get:
Generating development JavaScript bundle failed
Can't resolve 'fs' in '/home/gbiagini/Documents/work/appaltinnovativi/swg-service/node_modules/dotenv/lib'
If you're trying to use a package make sure that 'fs' is installed. If you're trying to use a local file make sure that the path is correct.
File: node_modules/dotenv/lib/main.js
failed Building development bundle - 13.100s
I don't get why the fs package should be an issue considering that I do the exact same process on gatsby-config.js and works flawlessly.
As you can see in Gatsby's documentation about Environment variables your client-side variables must be prefixed with GATSBY_ to make them available to the client.
Client-side JavaScript
For Project Env Vars that you want to access in
client-side browser JavaScript, you can define an environment config
file, .env.development and/or .env.production, in your root folder.
Depending on your active environment, the correct one will be found
and its values embedded as environment variables in the browser
JavaScript.
In addition to these Project Environment Variables defined in .env.*
files, you could also define OS Env Vars. OS Env Vars which are
prefixed with GATSBY_ will become available in browser JavaScript.
So, you will need to prefix your .env variables and update your code:
const keycloak = new Keycloak({
realm: process.env.GATSBY_KEYCLOAK_REALM,
url: process.env.GATSBY_KEYCLOAK_AUTH_URL,
clientId: process.env.GATSBY_KEYCLOAK_AUTH_CLIENT_ID
})

overwrite config file in nodejs - best practice?

Wondering what would be the best practice for my case.
I have a variable I need to set its value on app load and access this value many times across my code. what is the best way to get this value?
Right now I'm just overriding a config file property. Does a global variable is better? Is there another way to do this?
The priority standard for configs IMHO is:
command line parameter
environment var
local config file
global config file
if no cli parameter found, fall to look into environment vars, then local config file, then global
I do this.
Put the variable in .env file:
# .env
APP_PORT=4000
In my app source code, I create a file named constants.js:
// constants.js
import { load as loadEnvVars } from 'dotenv'; // run `npm i dotenv` to install
// load the .env file content to process.env
loadEnvVars();
// export the variables I need
export const APP_PORT = process.env.APP_PORT || 3000;
I import that file when I need it like this:
// server.js
import Express from 'express';
// import the constant
import { APP_PORT } from './constants';
const app = Express();
app.listen(APP_PORT, () => console.log('server deployed');

What is exports.local used for in node.js

Exports.local Node js sample code
I am using passport-local-mongoose in my node js Application and I come across exports.local for passport authentication. I couldn't understand it function. Please check the image above
In your case here there is nothing special about local keyword, it is just the name of the variable that is used to export the passport local authentication strategy configuration, so you can call it in other files using require, so here in your example, you have this logic written in authenticate.js, so to use it in any other file you will have to call it using the following:
const { local } = require('./authenticate'); // identify the right path to authenticate.js
enter code here
The CommonJS (CJS) format is used in Node.js and uses require and module.exports to define dependencies and modules. The npm ecosystem is built upon this format. In your case exports.local creates a new module and export it for the use elsewhere.
Example
user.js
const getName = () => {
return 'Jim';
};
exports.getName = getName;
index.js
const user = require('./user');
console.log(`User: ${user.getName()}`);
Output
User: Jim

How to add property to mocked module jest?

I have a module which is generated by webpack at build time called config.
// webpack.config.js
let devConfig = {url: 'https://localhost'}
...
externals: {
'config': JSON.stringify(devConfig),
},
I import and ise it like;
import config from 'config'
console.log(config.url)
How can I mock this module, and give the url during the test?
I've tried following. It's making config object avaliable but not url.
// __mocks__/config.js
jest.mock('config', ()=>({url: 'https://localhost'}), {virtual: true})
How can I add url propery to mocked module?
Thank you.
Note: I need url since I will need it when using nock.
Here it is;
Looks like something elese was preventing me.
jest.mock("Config", ()=> ({url: 'https://localhost'}), {virtual: true});

Categories

Resources