Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🟣 Data, Server और APIs  ·  Lesson 26

Environment Variables और next.config

Environment variables क्यों?

Passwords, API keys और URLs आपके laptop और live server पर अलग होते हैं। इन्हें code में लिखना खतरनाक (GitHub पर पहुँच जाते हैं) और inflexible है। Environment variables इन्हें code से बाहर रखते हैं।

Hard-coded

  • password: 'Str0ng#Pass'
  • GitHub पर push
  • हर जगह एक ही value
  • Leak = hack

Environment variable

  • password: process.env.DB_PASSWORD
  • हर machine पर अलग रहता है
  • हर environment में अलग
  • बदलना आसान
Secrets कभी hard-code न करें

.env files और उनका order

Project root
.env                 # defaults for all environments (can be committed if no secrets)
.env.development     # only for npm run dev
.env.production      # only for next build / next start
.env.local           # YOUR secrets – overrides the above – never commit
.env.example         # template for teammates (committed, fake values)
ENV – .env.local
# .env.local
DB_PASSWORD=Str0ng#Pass
SESSION_SECRET=ZmJ4b3Y5c2VjcmV0LWtleS1jaGFuZ2UtbWUtMTIzNDU2
SITE_URL=https://edusite.in
NEXT_PUBLIC_WHATSAPP=919000000000
process.env (असली server variables)सबसे ऊँची priority.env.local.env.development / .env.production.envसबसे कम priority
कौन सी value जीतती है

Server-only variables

JS – server पर env use करना
// lib/site.js  (EduSite) — read on the server
export const site = {
  name: 'EduSite',
  url: process.env.SITE_URL || 'http://localhost:3000',
  // …
}

// lib/db.js
password: process.env.DB_PASSWORD     // undefined in the browser – safe

NEXT_PUBLIC_ variables

सिर्फ़ NEXT_PUBLIC_ से शुरू होने वाले variables Client Components में मिलते हैं। Next.js उनकी value JavaScript bundle में copy कर देता है, इसलिए कोई भी उन्हें देख सकता है — वहाँ secrets कभी न रखें।

JSX – components/WhatsAppButton.jsx
// components/WhatsAppButton.jsx — Client Component
'use client'
export default function WhatsAppButton() {
  const number = process.env.NEXT_PUBLIC_WHATSAPP   // replaced with "919000000000" at build
  return (
    <a href={`https://wa.me/${number}?text=Hi, I want course details`}
       target="_blank" rel="noopener" className="btn">
      💬 Chat on WhatsApp
    </a>
  )
}
Browser bundleNEXT_PUBLIC_WHATSAPP ✅ सबको दिखता हैसिर्फ़ ServerDB_PASSWORD, SESSION_SECRET, SITE_URL 🔒
Browser क्या देख सकता है

Build time vs runtime

कहाँ useValue कब पढ़ी जाती हैबदलने के बाद…
Client code में NEXT_PUBLIC_BuildRebuild ज़रूरी
Static (○/●) pagesBuildRebuild ज़रूरी
Dynamic (ƒ) pages, actions, APIsहर requestServer restart

इसीलिए EduSite का README कहता है: npm run build से पहले SITE_URL set करें — sitemap और canonical URLs static हैं।

next.config.mjs समझें

JS – next.config.mjs (EduSite)
// next.config.mjs  (EduSite)
/** @type {import('next').NextConfig} */
const nextConfig = {
  // Simple permanent redirects (no code needed)
  async redirects() {
    return [{ source: '/home', destination: '/', permanent: true }]
  },
  images: {
    qualities: [75, 90],          // quality values the site uses
  },
}

export default nextConfig
JS – दूसरे काम के options
const nextConfig = {
  reactStrictMode: true,
  poweredByHeader: false,                      // hide "X-Powered-By: Next.js"
  trailingSlash: false,                        // /about not /about/
  output: 'standalone',                        // small server bundle for VPS/Docker
  async rewrites() {
    return [{ source: '/docs/:path*', destination: 'https://docs.example.com/:path*' }]
  },
  async headers() {
    return [{
      source: '/(.*)',
      headers: [
        { key: 'X-Content-Type-Options', value: 'nosniff' },
        { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
        { key: 'Permissions-Policy', value: 'camera=(), microphone=()' },
      ],
    }]
  },
}

Config में security headers

ऊपर का headers() function हर response में सुरक्षा वाले HTTP headers जोड़ता है — सस्ता security और "best practices" score boost।

आम गलतियाँ

  • Secret पर NEXT_PUBLIC_ prefix → पूरी दुनिया को दिख गया।
  • Hosting dashboard पर variables जोड़ना भूलना (Vercel → Settings → Environment Variables)।
  • Quotes और spaces: KEY = "value" → KEY=value लिखें।
  • next.config edit करके dev restart न करना → config सिर्फ़ start पर पढ़ा जाता है।

सारांश

  • Secrets .env.local में; template .env.example में।
  • सिर्फ़ NEXT_PUBLIC_* browser तक पहुँचता है, build time पर inline।
  • next.config.mjs: redirects, rewrites, headers, images, output।
✅ Practice

NEXT_PUBLIC_WHATSAPP और floating WhatsApp button जोड़िए। तीनों security headers जोड़कर DevTools → Network → Response Headers में check कीजिए।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

कौन सी .env file Git में commit करें?
सिर्फ़ dummy values वाली .env.example commit करें। .env.local या असली passwords/API keys वाली कोई file कभी commit न करें।
NEXT_PUBLIC_ variable बदलने के बाद भी पुराना क्यों दिखता है?
NEXT_PUBLIC_ values build time पर JavaScript में inline हो जाती हैं। बदलने के बाद npm run build फिर से चलाइए और redeploy कीजिए।
.env.local edit करने के बाद dev server restart करना पड़ता है?
Development में Next.js env files reload करता है, पर value update न हो तो npm run dev बंद करके फिर चलाइए।
← Next.js Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicMetadata और SEO आपकी प्रगति: 26 / 37 (70%) · Lesson 27 / 37 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें