Next.js Environment Variables Sinhala Guide | .env.local | NEXT_PUBLIC_

Next.js Environment Variables Sinhala Guide | .env.local | NEXT_PUBLIC_

Next.js Environment Variables කියන්නේ මොනවාද?

ආයුබෝවන් යාළුවනේ! අද අපි කතා කරන්න යන්නේ Next.js project එකක් කරන ඕනෑම කෙනෙකුට අත්‍යවශ්‍යම topic එකක් ගැන – ඒ තමයි Environment Variables. මේක හරියට අපේ ගෙදර තියෙන ආරක්ෂිත locker එකක් වගේ. වටිනා කියන දේවල්, එළියට පෙන්නන්න බැරි secrets, ඔය හැමදේම අපි ඒකේ තමයි තියන්නේ. Software project එකකදීත් එහෙමයි.

සරලවම කිව්වොත්, Environment Variables කියන්නේ අපේ code එක ඇතුළේ කෙලින්ම ලියන්න බැරි, ඒත් project එක run වෙන්න ඕන කරන configuration values. උදාහරණයක් විදිහට, Database connection string එකක්, API key එකක්, හෝ වෙනත් sensitive information එකක් වෙන්න පුළුවන්. මේවා code එකට hardcode කරන එක ඉතාම නරක පුරුද්දක් වගේම, security risk එකක්. ඒ වගේම, production, development, test වගේ විවිධ environments වලදී වෙනස් values use කරන්නත් මේවා උදව් වෙනවා.

Next.js මේ functionality එකට හොඳ support එකක් දෙනවා. අපි මේ tutorial එකෙන් බලමු කොහොමද Next.js project එකකදී මේ Environment Variables හරියටම පාවිච්චි කරන්නේ කියලා. සර්වර් පැත්තෙන් (server-side) සහ ක්ලයන්ට් පැත්තෙන් (client-side) මේවා access කරන විදිහ, security precautions සහ best practices ගැනත් අපි විස්තරාත්මකව කතා කරමු. එහෙනම් පටන් ගමු!

Server-side vs. Client-side Variables - වෙනස තේරුම් ගනිමු

Next.js වල Environment Variables ගැන කතා කරනකොට, අපිට මුලින්ම තේරුම් ගන්න ඕන කරන වැදගත්ම දේ තමයි Server-side සහ Client-side variables අතර තියෙන වෙනස. මේක හරියට අපේ ගෙදර ඇතුළේ තියෙන රහස් කාමරයක් (server-side) සහ එළියේ තියෙන සාමාන්‍ය කාමරයක් (client-side) වගේ.

Server-side Environment Variables

මේවා අපිට access කරන්න පුළුවන් වෙන්නේ Next.js application එකේ server-side code එකෙන් විතරයි. ඒ කියන්නේ getStaticProps, getServerSideProps, API Routes වගේ තැන්වලදී. මේවා browser එකට expose වෙන්නේ නැහැ. ඒ නිසා, API keys, database credentials වගේ ඉතාම sensitive data මේවා ඇතුළේ තියන්න පුළුවන්. මේවාට කිසිම විශේෂ prefix එකක් අවශ්‍ය වෙන්නේ නැහැ.

උදාහරණයක් විදිහට:

DB_HOST=localhost
DB_USER=root
API_SECRET=your_super_secret_api_key

මේවා client-side එකට පේන්නේ නැති නිසා ආරක්ෂිතයි.

Client-side Environment Variables (Public Variables)

මේවා අපිට server-side වගේම client-side (browser) code එකෙනුත් access කරන්න පුළුවන්. හැබැයි මේවාට NEXT_PUBLIC_ කියන prefix එක අනිවාර්යයෙන්ම එකතු කරන්න ඕනේ. මේ prefix එක දාපු ගමන් Next.js build process එකෙන් මේ variables ටික JavaScript bundle එකට inject කරනවා. ඒ කියන්නේ, මේවා browser එකෙන් inspect කරලා ඕනෑම කෙනෙකුට බලන්න පුළුවන්.

ඒ නිසා, කිසිම sensitive data එකක් NEXT_PUBLIC_ prefix එක එක්ක use කරන්න එපා! මේවා පාවිච්චි කරන්නේ public facing settings, වගේ දේවල් වලට.

උදාහරණයක් විදිහට:

NEXT_PUBLIC_ANALYTICS_ID=UA-XXXXX-Y
NEXT_PUBLIC_APP_NAME=My Awesome Next.js App
NEXT_PUBLIC_API_URL=https://api.example.com/v1

මේවා browser එකේ JavaScript code එකට direct access කරන්න පුළුවන්.

මතක තියාගන්න: NEXT_PUBLIC_ නැති ඕනෑම variable එකක් server-side විතරයි access කරන්න පුළුවන්. NEXT_PUBLIC_ තියෙන variables client-side එකටත් යනවා.

.env.local File එක පාවිච්චි කරමු

Next.js project එකකදී Environment Variables define කරන්න අපි ප්‍රධාන වශයෙන් .env.local file එක පාවිච්චි කරනවා. මේක තමයි මේ සඳහා තියෙන standard way එක.

.env.local file එක හදමු

ඔයාගේ Next.js project එකේ root directory එකේ .env.local කියලා අලුත් file එකක් හදන්න. (package.json, next.config.js තියෙන තැන).

ඊට පස්සේ ඒ file එක ඇතුළේ ඔයාගේ variables key=value format එකෙන් ලියන්න පුළුවන්.

# Server-side only environment variables (no NEXT_PUBLIC_ prefix)
DB_HOST=localhost
DB_USER=myuser
DB_PASSWORD=mypassword123
STRIPE_SECRET_KEY=sk_test_XXXXXXXXXXXXXXXXXXXXXXXX

# Public environment variables (accessible client-side, MUST have NEXT_PUBLIC_ prefix)
NEXT_PUBLIC_GOOGLE_ANALYTICS_ID=UA-XXXXX-Y
NEXT_PUBLIC_API_BASE_URL=https://api.yourapp.com
NEXT_PUBLIC_APP_VERSION=1.0.0

වැදගත්: .env.local file එක කවදාවත් Git repository එකට push කරන්න එපා! මේක .gitignore file එකට එකතු කරන්න ඕනේ. ඒකට පහත line එක .gitignore file එකට එකතු කරන්න:

# Local environment variables (should not be committed to Git)
.env*.local

මේකෙන් වෙන්නේ ඔයාගේ sensitive data Git වලට upload වීම වළක්වන එක.

.env.example file එකක් පාවිච්චි කරමු

දැන් ඔයා හිතන්න ඔයාගේ project එක වෙන කෙනෙක්ට දෙන්න ඕනේ කියලා. එතකොට එයාලාට .env.local file එකේ මොන variables ද තියෙන්න ඕනේ කියලා දන්නේ නෑනේ. ඒකට තමයි .env.example file එකක් පාවිච්චි කරන්නේ.

මේකෙදි අපි .env.local file එකේ තියෙන variables වල names විතරක්, dummy values එක්ක තියනවා. මේක Git එකට commit කරනවා. එතකොට project එක clone කරන අනිත් developers ලාට මේක reference එකක් විදිහට පාවිච්චි කරලා එයාලගේම .env.local file එක හදාගන්න පුළුවන්.

# .env.example file

# Server-side only environment variables
DB_HOST=your_db_host
DB_USER=your_db_user
DB_PASSWORD=your_db_password
STRIPE_SECRET_KEY=your_stripe_secret_key

# Public environment variables
NEXT_PUBLIC_GOOGLE_ANALYTICS_ID=your_google_analytics_id
NEXT_PUBLIC_API_BASE_URL=your_api_base_url
NEXT_PUBLIC_APP_VERSION=1.0.0

මේ .env.example file එක Git වලට commit කරන්න පුළුවන්.

Next.js වල Environment Variables Access කරන හැටි

දැන් අපි බලමු මේ variables අපේ code එක ඇතුළේ පාවිච්චි කරන්නේ කොහොමද කියලා. Next.js වලදී මේවා access කරන්න process.env object එක පාවිච්චි කරනවා.

Server-side (getStaticProps, getServerSideProps, API Routes)

server-side code එක ඇතුළේදී, අපි define කරපු ඕනෑම environment variable එකක් process.env.VARIABLE_NAME විදිහට direct access කරන්න පුළුවන්. NEXT_PUBLIC_ prefix එකක් අවශ්‍ය වෙන්නේ නැහැ.

getStaticProps එක ඇතුළේ

getStaticProps කියන්නේ build time එකේදී data fetch කරන්න පාවිච්චි කරන එකක්. මෙතනදී Server-side variables access කරන්න පුළුවන්.

// pages/products.tsx

import { GetStaticProps } from 'next';

interface Product {
  id: number;
  name: string;
}

interface ProductsProps {
  products: Product[];
}

const ProductsPage: React.FC<ProductsProps> = ({ products }) => {
  return (
    <div>
      <h1>Our Products</h1>
      <ul>
        {products.map((product) => (
          <li key={product.id}>{product.name}</li>
        ))}
      </ul>
    </div>
  );
};

export const getStaticProps: GetStaticProps = async () => {
  // Access a server-side only variable (e.g., a secret API key)
  const API_KEY = process.env.EXTERNAL_API_KEY; // No NEXT_PUBLIC_ prefix needed
  const API_URL = process.env.EXTERNAL_API_URL;

  if (!API_KEY || !API_URL) {
    console.error("Missing API Key or URL in getStaticProps");
    // Handle error, maybe return notFound or an empty array
    return { props: { products: [] } };
  }

  // Example: Fetch data using the secret API key
  const res = await fetch(`${API_URL}/products`, {
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
    },
  });
  const products: Product[] = await res.json();

  return {
    props: {
      products,
    },
    revalidate: 60, // Re-generate page every 60 seconds
  };
};

export default ProductsPage;

.env.local එකේ EXTERNAL_API_KEY සහ EXTERNAL_API_URL define කරලා තියෙන්න ඕනේ.

getServerSideProps එක ඇතුළේ

getServerSideProps කියන්නේ request time එකේදී data fetch කරන්න පාවිච්චි කරන එකක්. මේකත් server-side එකේ run වෙන නිසා Server-side variables access කරන්න පුළුවන්.

// pages/profile/[id].tsx

import { GetServerSideProps } from 'next';

interface UserProfileProps {
  user: { id: number; name: string; email: string; };
}

const UserProfile: React.FC<UserProfileProps> = ({ user }) => {
  if (!user) return <p>User not found.</p>;
  return (
    <div>
      <h1>User Profile</h1>
      <p>ID: {user.id}</p>
      <p>Name: {user.name}</p>
      <p>Email: {user.email}</p>
    </div>
  );
};

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { id } = context.query;
  const DB_CONNECTION_STRING = process.env.DB_CONNECTION_STRING; // Server-side only

  if (!DB_CONNECTION_STRING) {
    console.error("Database connection string is missing!");
    return { notFound: true };
  }

  // In a real application, you'd use the DB_CONNECTION_STRING to connect to your database
  // and fetch user data based on 'id'. For this example, we'll mock it.
  console.log(`Attempting to connect to DB using: ${DB_CONNECTION_STRING}`);
  const userData = {
    id: Number(id), // Cast id to number
    name: `User ${id}`,
    email: `user${id}@example.com`,
  };

  return {
    props: {
      user: userData,
    },
  };
};

export default UserProfile;

API Routes ඇතුළේ

API Routes කියන්නේ අපේ Next.js app එක ඇතුළේම backend API endpoints හදාගන්න පුළුවන් තැන. මේවා සම්පූර්ණයෙන්ම server-side run වෙන නිසා, ඕනෑම server-side environment variable එකක් ආරක්ෂිතව access කරන්න පුළුවන්.

// pages/api/send-email.ts

import type { NextApiRequest, NextApiResponse } from 'next';

type Data = { message: string };

export default function handler(req: NextApiRequest, res: NextApiResponse<Data>) {
  if (req.method === 'POST') {
    const { to, subject, body } = req.body;

    // Access a server-side only variable (e.g., an Email Service API Key)
    const EMAIL_SERVICE_API_KEY = process.env.EMAIL_SERVICE_API_KEY;

    if (!EMAIL_SERVICE_API_KEY) {
      console.error("Email service API key is not configured!");
      return res.status(500).json({ message: 'Email service configuration error.' });
    }

    // In a real app, you'd use this key to send an email via a third-party service
    console.log(`Sending email to ${to} with subject '${subject}' using key: ${EMAIL_SERVICE_API_KEY}`);
    // Example: call an external email sending API

    res.status(200).json({ message: 'Email sent successfully!' });
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

Client-side Components

Client-side (browser) code එක ඇතුළේදී, NEXT_PUBLIC_ prefix එකෙන් පටන් ගන්න variables විතරයි access කරන්න පුළුවන්. මේවා process.env.NEXT_PUBLIC_VARIABLE_NAME විදිහට access කරන්න ඕනේ.

// components/AnalyticsTracker.tsx

import { useEffect } from 'react';

const AnalyticsTracker: React.FC = () => {
  useEffect(() => {
    const analyticsId = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_ID;
    const appVersion = process.env.NEXT_PUBLIC_APP_VERSION;

    if (analyticsId) {
      console.log(`Initializing Google Analytics with ID: ${analyticsId}`);
      console.log(`App Version: ${appVersion}`);
      // In a real app, you'd load the Google Analytics script and track events
      // Example: window.gtag('config', analyticsId);
    } else {
      console.warn("Google Analytics ID is not set. Analytics will not be tracked.");
    }
  }, []);

  return null; // This component doesn't render anything visible
};

export default AnalyticsTracker;

නැවතත් මතක් කරනවා: NEXT_PUBLIC_ prefix එක දාපු variable එකක් browser එකෙන් ඕනෑම කෙනෙකුට බලන්න පුළුවන්. ඒ නිසා, කිසිම confidential information එකක් මේ විදිහට expose කරන්න එපා. බැංකු OTP එකක්, database password එකක් වගේ දේවල් කිසිම හේතුවක් මත Client-side එකට යවන්න එපා!

Best Practices, Security, සහ Troubleshooting Tips

Environment Variables effectively use කරන්න සහ security threats වලින් බේරෙන්න පහත tips ටික ගොඩක් වැදගත්:

1. Sensitive Information Client-side එකට Expose කරන්න එපා!

මේක තමයි රත්තරන් රීතිය! API_SECRET_KEY, DB_PASSWORD වගේ දේවල් කවදාවත් NEXT_PUBLIC_ prefix එක එක්ක use කරන්න එපා. ඒ වගේ secrets අවශ්‍ය නම්, ඒවා server-side (getStaticProps, getServerSideProps, API Routes) වල විතරක් පාවිච්චි කරන්න.

2. .env.local .gitignore කරන්න.

ඔයාගේ .env.local file එක (සහ .env.*.local pattern එක) .gitignore file එකට අනිවාර්යයෙන්ම එකතු කරන්න. මේකෙන් ඔයාගේ secrets Git repository එකට commit වීම වළක්වනවා. එහෙම නොකළොත්, ඔයාගේ secrets public වෙන්න පුළුවන්.

# .gitignore example

# Node modules
/node_modules

# next.js build output
.next/
out/

# Local environment variables
.env*.local

# ... other ignored files/folders

3. .env.example file එකක් පාවිච්චි කරන්න.

ඔයාගේ project එකේ අවශ්‍ය environment variables මොනවද කියලා අනිත් developers ලාට පහසුවෙන් දැනගන්න මේක උදව් වෙනවා. ඒක Git වලට commit කරන්න.

4. Build Time Variables vs. Runtime Variables

Next.js වල environment variables default build time එකේදී තමයි inject වෙන්නේ. ඒ කියන්නේ, ඔයා .env.local file එක modify කළොත්, වෙනස්කම් apply වෙන්න app එක නැවත build කරන්න ඕනේ.

Runtime variables (build කළාට පස්සේ run වෙනකොට වෙනස් කරන්න පුළුවන් variables) අවශ්‍ය නම්, Vercel වගේ hosting platforms වලදී platform settings හරහා හෝ Docker වැනි containerized deployments වලදී Dockerfile / runtime environment configurations හරහා manage කරන්න පුළුවන්. Next.js 12.2.0 ඉඳන් Runtime Environment Variables (for Node.js runtime) සඳහා experimental support එකක් තියෙනවා. ඒ ගැන වැඩි විස්තර නිල Next.js documentation එකෙන් බලාගන්න.

5. Troubleshooting - Missing Variables

සමහර වෙලාවට ඔයාට undefined results එන්න පුළුවන් process.env.YOUR_VAR කියල access කරනකොට. ඒ වගේ වෙලාවට මේ දේවල් check කරන්න:

  • .env.local file එකේ නම නිවැරදිද? (එක අකුරක් වරදින්න බැහැ)
  • Variable name එක නිවැරදිද? (case-sensitive)
  • NEXT_PUBLIC_ prefix එක හරියට දාලා තියෙනවද? (client-side variables වලට)
  • ඔයා app එක නැවත build කළාද? (npm run dev නැත්නම් npm run build) environment variables වෙනස් කළාට පස්සේ නැවත build කිරීම අත්‍යවශ්‍යයි.
  • console.log(process.env) කරලා බලන්න මොන variables ද available වෙන්නේ කියලා. (සැක සහිත variables වලට විතරක් කරන්න, මුළු object එකම log කරන එක හොඳ පුරුද්දක් නෙවෙයි, විශේෂයෙන් client-side එකේදී).

නිගමනය (Conclusion)

Next.js Environment Variables කියන්නේ අපේ applications වල security එක සහ maintainability එක වැඩි කරන ඉතාම වැදගත් feature එකක්. server-side variables සහ client-side variables අතර වෙනස හරියට තේරුම් ගැනීම, .env.local file එක නිවැරදිව පාවිච්චි කිරීම, සහ .gitignore, .env.example වගේ best practices follow කිරීමෙන් අපිට powerful, secure Next.js applications හදන්න පුළුවන්.

ඉතින් යාළුවනේ, මේ tutorial එක ඔයාලට ප්‍රයෝජනවත් වෙන්න ඇති කියලා හිතනවා. Next.js project එකක් කරනකොට මේ දේවල් මතක තියාගෙන වැඩ කරන්න. මොකද මේවා නොදැන කරන පොඩි වැරැද්දකින් උනත් project එකට ලොකු හානියක් වෙන්න පුළුවන්.

ඔයාලා මේක Try කරලා බලලා ඔයාලගේ අත්දැකීම් පහළ Comment section එකේ ලියන්න. ප්‍රශ්න තියෙනවා නම් අහන්න! අපි උදව් කරන්න ලෑස්තියි!

සංවර්ධනයට ජයවේවා!