惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Spread Privacy
Spread Privacy
V
Visual Studio Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recorded Future
Recorded Future
云风的 BLOG
云风的 BLOG
Microsoft Azure Blog
Microsoft Azure Blog
I
InfoQ
Apple Machine Learning Research
Apple Machine Learning Research
MyScale Blog
MyScale Blog
M
MIT News - Artificial intelligence
WordPress大学
WordPress大学
Recent Announcements
Recent Announcements
V
V2EX
The GitHub Blog
The GitHub Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
V
Vulnerabilities – Threatpost
C
Check Point Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
AI
AI
宝玉的分享
宝玉的分享
P
Proofpoint News Feed
量子位
Attack and Defense Labs
Attack and Defense Labs
H
Hackread – Cybersecurity News, Data Breaches, AI and More
P
Privacy International News Feed
Google DeepMind News
Google DeepMind News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
CERT Recently Published Vulnerability Notes
腾讯CDC
Latest news
Latest news
Google DeepMind News
Google DeepMind News
The Register - Security
The Register - Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
G
GRAHAM CLULEY
Blog — PlanetScale
Blog — PlanetScale
博客园_首页
美团技术团队
The Cloudflare Blog
T
Tenable Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
J
Java Code Geeks
SecWiki News
SecWiki News
Webroot Blog
Webroot Blog
N
News | PayPal Newsroom
博客园 - 叶小钗
博客园 - Franky

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Environment Variables in JavaScript: process.env
Dmitri Pavlutin · 2023-02-08 · via Dmitri Pavlutin Blog
Post cover

The environment variables are defined outside of the JavaScript execution context.

There's a set of environment variables defined by the OS, for example:

  • USER: the current user
  • HOME: the current user's home path
  • PWD: the current working directory
  • PATH: directories to search in order to execute a command

In terms of the JavaScript and Node.js ecosystem, the following variables are common:

  • NODE_ENV: determines if the script runs in development or production mode. Usually takes one of the values: production, prod, development, dev, or test
  • PORT: the port the running application will use (e.g. 3000, 8080, etc.)

Let's see how you can access these environment variables (either OS or Node.js specific) in a JavaScript file.

1. process.env object

When executing a JavaScript file as a Node CLI (command line interface) command, Node creates a special process.env object that contains the environment variables as properties.

For example, let's execute the JavaScript file main.js in the command line:


cd /home/dmitri/

NODE_ENV=production node main.js


Where main.js file contains the following code:


// /home/dmitri/main.js

console.log(process.env.USER); // dmitri

console.log(process.env.PWD); // /home/dmitri/

console.log(process.env.NODE_ENV); // production


process.env.USER is the operating system user name that executes the command. The variable has a value of 'dmitri' because this is my OS user name.

process.env.PWD contains the absolute path to the current working directory. Since the executed file path is /home/dmitri/main.js, then the current working directory is /home/dmitri/.

The above variables are taken from the environment of the operating system.

process.env.NODE_ENV variable equals 'production'. This variable is defined by the prefix NODE_ENV=production of the command NODE_ENV=production node main.js.

If you'd like to provide local defaults to certain environment variables, then check the dotenv project.

2. process.env in a browser environment

The environment variables, including process.env, are accessible to scripts running in the CLI.

process.env, however, is not available in a browser environment.

Fortunately, exposing environment variables to the browser runtime can be done using bundlers. Let's take a look at how it's done using Vite and webpack.

2.1 Vite

Vite exposes a predefined set of variables through import.meta.env object:

  • import.meta.env.MODE: is either 'development' or 'production'
  • import.meta.env.PROD: is true in production mode
  • import.meta.env.DEV: is true in development mode
  • import.meta.env.SSR: is a boolean whether the app runs on the server side
  • import.meta.env.BASE_URL: the base URL

On top of that, Vite can also load variables from .env file. Under the hood, Vite uses dotenv. But you don't have to manually call anything related to dotenv: Vite does everything for you.

For example, having an .env file like this:

then you can access this value in the browser at runtime import.meta.env.VITE_MY_VAR, which will be 'value'.

Note that Vite exposes publicly only variables starting with VITE_ prefix (but this can be configured).

In the demo the environment variables provided by Vite are rendered on the webpage.

Vite has a detailed guide on how to access the environment variables.

2.2 webpack

The built-in plugin EnvironmentPlugin exposes environment variables in webpack.

For example, to expose the NODE_ENV env variable, you can use the following configuration:


// webpack.config.js

const { EnvironmentPlugin } = require('webpack');

module.exports = {

// ...

plugins: [

// ...

new EnvironmentPlugin(['NODE_ENV'])

]

}


Open the demo. NODE_ENV variable was exposed by webpack and is rendered on the webpage.

If NODE_ENV variable is not available in the environment, the plugin will throw an error. But you can assign a default value to a variable using a plain JavaScript object as a config (with the value being the default value):


// webpack.config.js

const { EnvironmentPlugin } = require('webpack');

module.exports = {

// ...

plugins: [

// ...

new EnvironmentPlugin({

NODE_ENV: 'development'

})

]

}


With the above configuration, if NODE_ENV variable isn't set up, webpack defaults process.env.NODE_ENV to development.

3. Conclusion

A JavaScript file executed in Node CLI can access the environment variables using the special object process.env.

For example, process.env.USER contains the user name that executes the script.

The environment variables are not available at runtime in a browser. But modern bundlers like Vite and webpack can expose certain variables.

For example, Vite exposes the current running mode using import.meta.env.MODE. In webpack EnvironmentPlugin lets you expose the necessary variables.

What env variables do you find useful during runtime?

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉, developing a gift boxes Shopify app, and blogging about Shopify. Living in the sunny Barcelona. 🇪🇸