In this article, we analyse a code snippet from next-runtime-env that applies regular expression test in Array.prototype.filter function. next-runtime-env populates your environment at runtime rather than build time, it is an open-source project written by ExpatFile.
The below code snippet is picked from helpers/public-env.ts.
import { ProcessEnv } from '../typings/process-env';
/**
* Gets a list of environment variables that start with `NEXT_PUBLIC_`.
*/
export function getPublicEnv() {
const publicEnv = Object.keys(process.env)
.filter((key) => /^NEXT_PUBLIC_/i.test(key))
.reduce(
(env, key) => ({
…env,
[key]: process.env[key],
}),
{} as ProcessEnv,
);
return publicEnv;
}
Let’s analyse what’s happening in this function.
Object.keys(process.env)
Object.keys(process.env)
returns an array of environment key names since process.env is an object. For example, say you have the below in your .env in your Next.js project.
NEXT_PUBLIC_SUPABASE_ANON_KEY=id_123
DATABASE_URL=https://some-database-url
When you do Object.keys(process.env)
based on the above .env file, you will have an array containing the key names.
[
"NEXT_PUBLIC_SUPABASE_ANON_KEY",
"DATABASE_URL"
]
filter with regex test
In Next.js, if your environment variable name is prefixed with NEXT_PUBLIC_
, it is exposed to the public and can be found in the build. In the below code snippet, filter applies regex test to get the env variables prefixed with NEXT_PUBLIC_
.
.filter((key) => /^NEXT_PUBLIC_/i.test(key))
This way, you will have an array of env variable names prefixed with NEXT_PUBLIC_. Read more about regular expression test.
reduce
reduce
in the below code snippet is used to generate an JSON object that only contains env variable names prefixed with NEXT_PUBLIC_
, in other words, public env variables that are exposed in build.
.reduce(
(env, key) => ({
…env,
[key]: process.env[key],
}),
{} as ProcessEnv,
);
Read more about Array.prototype.reduce
About us:
We study large open source projects and provide free architectural guides.
We have developed free, reusable Components, built with tailwind, that you can use in your project.
We analyze open-source code and provide courses so you can learn various advanced techniques and improve your skills. Get our courses.
Subscribe to our Youtube to get the insights from open-source projects, where we review code snippets.
References:
https://github.com/expatfile/next-runtime-env/blob/development/src/script/public-env-script.tsx
https://github.com/expatfile/next-runtime-env/blob/development/src/helpers/get-public-env.ts#L6
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Top comments (0)