Here's how next-runtime-env applies regex test in Array.prototype.filter()
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.
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.
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 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.
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.