2 min read
·
0 views

process.env vs import.meta

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.

config.js

_10
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 that uses the query parameters with the import syntax.


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

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


_10
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

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