Challenge your understanding of environment variables and configuration techniques in Next.js projects. Assess your ability to manage, scope, and access runtime configuration for secure and scalable applications.
Which prefix must an environment variable have to be exposed to the browser in a Next.js application?
Explanation: Only variables prefixed with NEXT_PUBLIC_ are automatically exposed to the browser in Next.js. Option PUBLIC_NEXT_ looks similar but is invalid. CLIENT_ENV_ and FRONTEND_ are not recognized prefixes and won’t expose environment variables to the browser. Using the correct prefix helps prevent accidental leaks of sensitive server-side data.
What is a key characteristic of environment variables in Next.js when used in getStaticProps at build time?
Explanation: Environment variables accessed during getStaticProps are injected at build time, making them immutable until a new build is triggered. The second option is incorrect, as build-time variables can't be changed without redeploying. The third distractor confuses serverless execution specifics. The last option is wrong because getStaticProps runs on the server side, not client-side rendering.
Given multiple environment files such as .env, .env.local, and .env.production, which file takes precedence in Next.js when all are present in a production build?
Explanation: .env.production is prioritized for a production build, ensuring production-specific variables overwrite those in other files. While .env.local is loaded last for non-production environments, it is ignored during production for security. .env is the base file with lowest priority, and .env.development applies only to development builds.
If you have a variable called SECRET_KEY declared in your .env file, can it ever be accessed directly in client-side code?
Explanation: By default, only environment variables prefixed with NEXT_PUBLIC_ are exposed to client-side code, protecting sensitive information like SECRET_KEY. Option two is incorrect because not all .env variables are exposed frontend. The third option misunderstands how environment variables are managed in such frameworks. The fourth option is not true, as NODE_ENV being set to 'test' does not affect the scoping rules.
Which approach allows you to use different environment variable values based on the deployment environment (e.g., development, test, production) without changing source code?
Explanation: Defining distinct environment files (like .env.development, .env.production) and setting NODE_ENV ensures variable values are chosen automatically per environment. Hardcoding in components removes flexibility and security. Editing a single .env for each deployment is error-prone and inefficient. Declaring variables on the window object is insecure and bypasses structured configuration.