Utilities

The SSK-Core utilities module provides essential helper functions designed to streamline environment management, client/server detection, and secure access to environment variables. These utilities are a core part of SSK-Core's functionality, simplifying tasks that are commonly needed across different areas of your project.


Core Features

  1. Environment Detection: Easily determine if the code is running in a development environment or whether it’s executing on the client (browser) or server (Node.js).

  2. Dynamic Host Retrieval: Automatically retrieve the host URLs depending on whether you’re working locally or in a production environment, making it simple to manage local and production setups.

  3. Environment Variable Access: Securely fetch and validate environment variables with flexible error handling. This reduces the chance of runtime failures by ensuring that essential variables are always available in production environments.


How to Use

1. Client-Side Environment Variable Validation

Use checkRequiredEnvVar to ensure critical environment variables are defined on the client side. It allows for flexible handling during development and strict enforcement in production.

Example:

import { checkRequiredEnvVar } from '@core/utils'

const apiUrl = checkRequiredEnvVar(
  'NEXT_PUBLIC_API_URL',
  process.env.NEXT_PUBLIC_API_URL,
)
console.log(`API URL: ${apiUrl}`)
  • Development Behavior: Logs an error if the variable is missing but allows you to continue.

  • Production Behavior: Throws an error if the variable is missing, preventing potentially unstable behavior.


2. Server-Side Environment Variable Retrieval

Use getEnvVar to safely fetch and validate environment variables in server-side code. This utility ensures secure access and avoids unintended exposure of environment variables to the client.

Example:

import { getEnvVar } from '@core/utils'

const dbConnectionString = getEnvVar('DATABASE_URL')
console.log(`Database Connection String: ${dbConnectionString}`)
  • Server-Side Only: Throws an error if used on the client side.

  • Integrated Validation: Automatically leverages checkRequiredEnvVar for robust validation.


Other Utilities

Development Environment Check

Verify if the project is running in a development environment:

if (checkIsDev()) {
  console.log('Development mode is active')
}

Host URL Retrieval

Retrieve the appropriate host URL based on the environment using getHost:

const currentHost = getHost()
console.log(`Current host: ${currentHost}`)

This feature ensures that both local development and production environments are handled seamlessly, reducing issues with hardcoded URLs.


By leveraging these utilities, you can streamline environment management, improve development efficiency, and ensure a smooth transition between local and production environments.

Last updated