Web Development

Crystal Environment Variables

Using Environment Variables

Crystal environment variables use ENV for configuration.

Introduction to Environment Variables

Environment variables are key-value pairs used to configure applications without hardcoding values directly into the source code. In Crystal, environment variables are accessed using the ENV module, providing a flexible way to manage application settings across different environments.

Accessing Environment Variables in Crystal

To access environment variables in a Crystal program, you can use the ENV module. This module allows you to retrieve environment variable values using the variable's name as the key.

For example, to access an environment variable named DATABASE_URL, you would use the following syntax:

Setting Default Values

Sometimes, an environment variable might not be set, and you want to ensure your application can still function. You can provide a default value using the || operator.

Here's how you can set a default value for DATABASE_URL:

Checking for Environment Variable Existence

Before using an environment variable, you might want to check if it exists. This can be done using the ENV["VAR_NAME"]? method, which returns nil if the variable is not set.

Example:

Setting Environment Variables Programmatically

While environment variables are typically set in the operating system, you can also set them programmatically within a Crystal application. This is useful for testing or temporary configuration changes.

To set an environment variable, use the following syntax:

Use Cases for Environment Variables

Environment variables are commonly used for configuration settings such as:

  • Database connection strings
  • API keys
  • Service endpoints
  • Application modes (e.g., development, production)

They allow developers to change the behavior of applications without modifying the code, making it easier to manage different environments.

Next
CORS