Reference server-side environment variables in OpenShift when using client-side JavaScript libraries

Because application images are prebuilt for use in containers, using server-defined environment variables in client-side scripts seems impossible. However, there is a way to inject variable values at runtime, and this learning path, created by Don Schenck, reveals one method.

Overview: Reference server-side environment variables in OpenShift when using client-side JavaScript libraries

Create an OpenShift Serverless function

Application images are built using Podman (or Docker) as directed in a configuration file — Containerfile or Dockerfile. To add some flexibility, you can specify local environment variables to be used during the build process. You can also specify environment variables to be used at runtime. However, because the runtime environment is on a server, using the environment variable values in client-side scripts seems impossible. In a best-case scenario, values would be injected into the client script just prior to the script being sent to the client (i.e., your browser).

Using environment variables at runtime is especially valuable during development and testing, and is a technique you might wish to employ in production. Using some runtime scripting and common Linux commands, it is possible to send server environment variables to the client.

This learning path reveals an approach to solving this problem and demonstrates one particular implementation of this solution.

Prerequisites

You will need the following to complete this activity:

What you will do

In this learning path, you will:

  • Create a back-end Quote Of The Day web service
  • Create a secured route to web service
  • Get a URL to back-end web service
  • Start a front-end, qotd-frontend application using environment variables
  • View the results

What you will learn

When you have finished this learning path, you will understand:

  • How to use runtime scripting
  • How to use server-side environment variables in your client-side JavaScript

How long will this activity take?

  • About 30-45 minutes 

Programming languages

  • You don’t need to know any programming languages to complete this task.
  • If you’re interested in viewing the code, the back end is written in Go, the front end is in HTML and JavaScript, served using Nginx.

If you need help

If you get stuck, if something isn’t working, or you simply have questions, you can easily contact us via email at devsandbox@redhat.com.