Backend Development 14 min read

Design and Implementation of an Environment Labeling Solution for Middle‑Back Office Systems

This article details a practical solution that adds environment identifiers via Nginx response headers and front‑end detection to clearly distinguish test, sandbox, and production environments in middle‑back office applications, reducing confusion and operational errors.

大转转FE
大转转FE
大转转FE
Design and Implementation of an Environment Labeling Solution for Middle‑Back Office Systems

In daily development and testing, team members often doubt whether they are in a test environment, leading to communication overhead and potential operational hesitation.

To eliminate this confusion, a comprehensive environment labeling scheme was devised for middle‑back office systems, clearly separating test, sandbox, and production environments so users can instantly recognize the current system context.

Initially, a generic API was considered to convey environment data, but multiple interfaces with varied proxy settings made this approach impractical. Instead, the solution leverages Nginx to inject a dedicated response header for each API, indicating the Docker environment regardless of proxy configurations.

Solution Design : Nginx adds an environment tag to every response header; the front‑end reads this tag and displays a visual indicator. This method is simple, efficient, and avoids complex back‑end logic.

Configuration Options (adjustable via API):

domain: the domains to monitor (supports multiple);
insertDefaultDomClassOrID: custom DOM selector for placing the label;
customStyle: style overrides (size, color, background, etc.);
isShowOnline: toggle display in production (default false);
isCollapseHide: hide label when side menu collapses;
isShowFrontEnvironment: show front‑end environment label for debugging.

These options allow fine‑grained control to fit diverse project needs.

Compatibility – Route Change Handling : When users navigate to a new route, any previously shown environment popup is automatically hidden and old data cleared to prevent stale information.

// Listen for hash changes and reset the modal
window.onhashchange = function () {
  const newHash = window.location.hash;
  if (newHash) {
    const $modal = document.querySelector('.modal-distring-environment');
    if ($modal) $modal.style.display = 'none';
    clickHistory = [];
    isModalVisible = false;
  }
};

Compatibility – Refresh Popup Issue : The original implementation used innerHTML and display toggles, which could leave the popup visible due to lingering visibility . The revised code ensures proper toggling of both display and visibility and only updates content when the modal is shown.

const createModalData = (current, url) => {
  const $modal = document.querySelector('.modal-distring-environment');
  if (currentEnvir != current) {
    const content = '接口' + extractUrlParts(url) + '与当前环境不一致
';
    if (!clickHistory.includes(content)) clickHistory.push(content);
    $modal.innerHTML = clickHistory.join('');
  }
};

MutationObserver vs. Timer : To address DOM update latency, a MutationObserver replaces setTimeout‑based polling, offering precise, efficient detection of DOM changes without unnecessary timers.

const observeDom = (selector, el) => {
  const observer = new MutationObserver(mutations => {
    mutations.forEach(mutation => {
      if (mutation && !document.querySelector('.pc-distring-environment')) {
        // ...handle changes...
        observer.disconnect();
      }
    });
  });
  const config = { attributes: true, childList: true, subtree: true };
  observer.observe(document.body, config);
  observer.takeRecords();
};

Wildcard Domain Support : By extracting the hostname from each request URL and normalizing subdomains, the system correctly identifies environments even when accessed via wildcard domains such as a-xxx.test.yyy.com .

const transformSubdomain = (originalUrl, domain) => {
  let hostname = new URL(originalUrl).hostname;
  let modifiedUrl = originalUrl.replace(/-[^.]+\.[^.]+/, '');
  return hostname.includes('-') ? modifiedUrl : originalUrl;
};

Iframe Compatibility : When the page runs inside an iframe (i.e., window.self !== window.top ), the environment detection is disabled to avoid false labeling.

**Summary and Outlook**: The environment labeling feature has been successfully deployed across core backend projects, receiving positive feedback from testing and development teams. Ongoing efforts focus on expanding adoption to additional business lines, incorporating feedback, and continuously refining the solution to meet evolving requirements.

JavaScriptMutationObservernginxenvironment labelingfrontend detectionresponse headerwildcard domain
大转转FE
Written by

大转转FE

Regularly sharing the team's thoughts and insights on frontend development

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.