Logo
BlogDashboardAboutProjects
Logo
HomeBlogDashboardAboutProjects
GithubGithub
LinkedinLinkedin
TwitterTwitter
v1.12.1
11 Nov 2023
·
2 min read

process.env vs import.meta: environment variables in Node and the browser

process.env only runs in Node. It won't work in the browser. import.meta is the module-aware alternative, and it works with TypeScript too.

process.env

The process.env is a global variable that is only used by Node at runtime and this can only be used in node and not in the browser. This is the most familiar way to handle environment variables that we do not want to commit into git that could expose some serious sensitive information.

Following is an example of how we use process.env and usually being used during build time.

const DATABASE_URL = process.env.DATABASE_URL;

import.meta

import.meta is an object that is bundled with the JavaScript Modules. It contains information about the module and is extensible.

The following is an example from MDN Docs that uses the query parameters with the import syntax.

<script type="module">
  import "./index.mjs?someParams=foo";
</script>

The index.mjs module is able to read the parameters someParams using the import.meta syntax

new URL(import.meta.url).searchParams.get("someParams"); // foo

This is something new to me in which it cannot be done when using process.env

TypeScript support for import.meta

For those who prefer to use TypeScript, we can create the relevant types through a global file - env.d.ts in the root of the project.

// env.d.ts
interface ImportMetaEnv {
  SOME_ENV_VARIABLE: string;
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}

Related Articles

23 Nov 2023
2 tags
What the ! operator does in TypeScript and Swift
The ! at the end of a TypeScript expression tells the compiler you know the value isn't null or undefined. It's the same idea as force unwrapping in Swift. Useful, but worth understanding before reaching for it.
23 Jan 2023
1 tag
Adding JSON-LD structured data to your React blog
Google uses structured data to understand what's on your page. JSON-LD is the recommended format. Here's a minimal React component to add it, and how to verify it works.
19 Jan 2023
1 tag
Using the Web Share API to trigger the OS share sheet
Instead of building a custom share UI, you can hand off to the OS share sheet with one function call. navigator.share() works on mobile browsers. Here's how to use it.
29 Mar 2023
1 tag
Feature flags: ship code without shipping features
A feature flag is an if/else around a piece of code, controlled by an environment variable. It lets you merge and deploy work-in-progress without turning it on. Fewer conflicts, safer releases.