The correct way to manage environment variables in Next.js applications is to use named specifications .env files and ensure security. 1. Create .env files of different environments such as .env.local, .env.development, .env.production and .env.test, where variables prefixed with NEXT_PUBLIC_ will be exposed to the client; 2. Access variables securely in the code, always provide default values to prevent missing, and only use non-public variables on the server side; 3. Configure environment variables through deployment platforms (such as Vercel, Netlify or cloud services) in the production environment to avoid dependency files; 4. Add sensitive files such as .env.local to .gitignore to prevent leakage; 5. Use verification logic to check necessary variables at startup, which can be implemented through a custom config module; 6. Note that statically generated pages solidify environment variables when building. Dynamic configuration needs to be obtained through API routing or client requests, ultimately ensuring that sensitive information does not enter the front-end code and the configuration is maintained.
Handling environment variables in a Next.js app is essential for managing configuration across different environments—like development, staging, and production—without exposing sensitive data. Here's how to do it properly and securely.

Use .env
Files with Proper Naming
Next.js supports .env
files out of the box. You can create different files for different environments:
-
.env.local
– Local environment variables (used in all environments, not committed to version control) -
.env.development
– Only loaded in development -
.env.production
– Only loaded in production -
.env.test
– Used during testing
?? Important : Only variables prefixed with
NEXT_PUBLIC_
are exposed to the browser. Others are kept server-side and not accessible on the client.![]()
Example .env.local
:
# Server-side only (safe for secrets) API_SECRET=your_secret_key DATABASE_URL=postgresql://user:pass@localhost:5432/mydb # Client-side accessible NEXT_PUBLIC_API_URL=https://api.example.com NEXT_PUBLIC_ANALYTICS_ID=ga-123456
These values can then be accessed in your code:

// Accessible anywhere console.log(process.env.NEXT_PUBLIC_API_URL); // Only available on the server (eg, API routes, getStaticProps, etc.) console.log(process.env.API_SECRET);
Access Environment Variables Safely
Always assume environment variables might be undefined, especially during build or if misconfigured.
? Good practice – provide fallbacks :
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api';
? Avoid direct usage without checks:
// Risky if variable is missing fetch(`${process.env.API_URL}/users`);
Also, remember:
- Client-side : Only
NEXT_PUBLIC_
variables are available. - Server-side (Node.js context) : All variables (including non-prefixed ones) are available.
This includes:
-
getStaticProps
-
getServerSideProps
- API routes
-
middleware.js
Set Environment Variables in Production
During deployment, avoid relying on .env
files in production. Instead:
Use your hosting platform's environment variable UI or CLI :
- Vercel : Go to Project Settings → Environment Variables
- Netlify : Site Settings → Build & Deploy → Environment
- AWS, GCP, Docker, etc. : Set via deployment config or orchestration tools
Never commit
.env.local
Add it to.gitignore
:.env.local *.env.local
For CI/CD pipelines, inject secrets via encrypted environment variables or secret managers.
Validate Required Environment Variables
You can add a validation step at startup to catch missing critical variables.
Create a helper, eg, lib/env.js
:
const required = (name) => { if (!process.env[name]) { throw new Error(`Missing environment variable: ${name}`); } return process.env[name]; }; export const config = { apiUrl: required('NEXT_PUBLIC_API_URL'), analyticsId: process.env.NEXT_PUBLIC_ANALYTICS_ID, apiSecret: required('API_SECRET'), // Only used server-side };
Then import config
in your API routes or config files to ensure early failure if something's missing.
Bonus: Runtime vs Build-Time Variables
Build-time variables : Defined when the app is built (
next build
).
Used ingetStaticProps
and static generation.Runtime variables : For server-rendered or API routes, values are read at request time.
This means you can update secrets without rebuilding (if your hosting support dynamic env vars).
?? Static pages (ISR or SSG) will bake in environment values at build time. So if you rely on dynamic configuration, consider using API routes or client-side fetching.
Basically, stick to the NEXT_PUBLIC_
rule, keep secrets out of client code, validate inputs, and manage production variables through your deployment platform. It's simple but easy to mess up—so be deliberate.
The above is the detailed content of How to Handle Environment Variables in a Next.js App. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

ARIAattributesenhancewebaccessibilityforuserswithdisabilitiesbyprovidingadditionalsemanticinformationtoassistivetechnologies.TheyareneededbecausemodernJavaScript-heavycomponentsoftenlackthebuilt-inaccessibilityfeaturesofnativeHTMLelements,andARIAfill

React itself does not directly manage focus or accessibility, but provides tools to effectively deal with these issues. 1. Use Refs to programmatically manage focus, such as setting element focus through useRef; 2. Use ARIA attributes to improve accessibility, such as defining the structure and state of tab components; 3. Pay attention to keyboard navigation to ensure that the focus logic in components such as modal boxes is clear; 4. Try to use native HTML elements to reduce the workload and error risk of custom implementation; 5. React assists accessibility by controlling the DOM and adding ARIA attributes, but the correct use still depends on developers.

Let’s talk about the key points directly: Merging resources, reducing dependencies, and utilizing caches are the core methods to reduce HTTP requests. 1. Merge CSS and JavaScript files, merge files in the production environment through building tools, and retain the development modular structure; 2. Use picture Sprite or inline Base64 pictures to reduce the number of image requests, which is suitable for static small icons; 3. Set browser caching strategy, and accelerate resource loading with CDN to speed up resource loading, improve access speed and disperse server pressure; 4. Delay loading non-critical resources, such as using loading="lazy" or asynchronous loading scripts, reduce initial requests, and be careful not to affect user experience. These methods can significantly optimize web page loading performance, especially on mobile or poor network

Shallowrenderingtestsacomponentinisolation,withoutchildren,whilefullrenderingincludesallchildcomponents.Shallowrenderingisgoodfortestingacomponent’sownlogicandmarkup,offeringfasterexecutionandisolationfromchildbehavior,butlacksfulllifecycleandDOMinte

StrictMode does not render any visual content in React, but it is very useful during development. Its main function is to help developers identify potential problems, especially those that may cause bugs or unexpected behavior in complex applications. Specifically, it flags unsafe lifecycle methods, recognizes side effects in render functions, and warns about the use of old string refAPI. In addition, it can expose these side effects by intentionally repeating calls to certain functions, thereby prompting developers to move related operations to appropriate locations, such as the useEffect hook. At the same time, it encourages the use of newer ref methods such as useRef or callback ref instead of string ref. To use Stri effectively

Create TypeScript-enabled projects using VueCLI or Vite, which can be quickly initialized through interactive selection features or using templates. Use tags in components to implement type inference with defineComponent, and it is recommended to explicitly declare props and emits types, and use interface or type to define complex structures. It is recommended to explicitly label types when using ref and reactive in setup functions to improve code maintainability and collaboration efficiency.

There are three key points to be mastered when processing Vue forms: 1. Use v-model to achieve two-way binding and synchronize form data; 2. Implement verification logic to ensure input compliance; 3. Control the submission behavior and process requests and status feedback. In Vue, form elements such as input boxes, check boxes, etc. can be bound to data attributes through v-model, such as automatically synchronizing user input; for multiple selection scenarios of check boxes, the binding field should be initialized into an array to correctly store multiple selected values. Form verification can be implemented through custom functions or third-party libraries. Common practices include checking whether the field is empty, using a regular verification format, and displaying prompt information when errors are wrong; for example, writing a validateForm method to return the error message object of each field. You should use it when submitting

Server-siderendering(SSR)inNext.jsgeneratesHTMLontheserverforeachrequest,improvingperformanceandSEO.1.SSRisidealfordynamiccontentthatchangesfrequently,suchasuserdashboards.2.ItusesgetServerSidePropstofetchdataperrequestandpassittothecomponent.3.UseSS
