Environment Variables

Environment variables are a secure way to store and manage configuration data or sensitive information, such as API keys, database connection strings, or environment-specific settings. In Next.js, environment variables are defined in .env file and can be accessed during build time or runtime, depending on their prefix.

1. Setting Up Environment Variables

The template already comes with a .env file located in the root directory. Modify these variables as needed. Example:

NEXT_PUBLIC_API_BASE_URL=https://api.example.com
DATABASE_URL=postgres://user:password@localhost:5432/db_name
2. Understanding Environment Variable Types
  • Public Variables: Variables prefixed with NEXT_PUBLIC_ are exposed to the browser. These should not include sensitive data.
  • Private Variables: Variables without the NEXT_PUBLIC_ prefix are only available on the server side and are never exposed to the client.
3. Accessing Environment Variables
🔹 Server-Side Access

Access private variables in server-side functions like API routes or Server Components:

export async function GET() {
    const databaseUrl = process.env.DATABASE_URL;
    return new Response('Database URL: ' + databaseUrl);
}
🔹 Client-Side Access

Access public variables in your React components:

'use client';

import { useEffect } from 'react';

const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL;

export default function ShowApiUrl() {
    useEffect(() => {
        console.log('API Base URL:', apiBaseUrl);
    }, []);

    return 

API URL: {apiBaseUrl}

; }
4. Official Documentation

For more details, refer to the official Next.js Environment Variables documentation.

Receive the latest updates directly in your inbox!

Be the first to know about new updates and exclusive discounts. No spam, just great offers!

How about

A Custom Project?

With over 7 years of experienced team, we specialize in delivering custom projects for startups, blue-chip companies, and government agencies. We have successfully completed over 250+ projects, providing tailored solutions that meet the unique needs of each client.

Hire Us
Domiex Admin & Dashboards
230+

Total Pages

5+

Layouts

11+

Application

We provide quick support withing one business day to all of our customers.

© Domiex Created & Crafted by SRBThemes.