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.
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
NEXT_PUBLIC_
are exposed to the browser. These should not include sensitive data.NEXT_PUBLIC_
prefix are only available on the server side and are never exposed to the client.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); }
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}
; }
For more details, refer to the official Next.js Environment Variables documentation.
Be the first to know about new updates and exclusive discounts. No spam, just great offers!
How about
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 Created & Crafted by SRBThemes.