Skip to content

Allow custom prefix#17

Merged
Crell merged 15 commits intomasterfrom
allow-custom-prefix
Feb 5, 2021
Merged

Allow custom prefix#17
Crell merged 15 commits intomasterfrom
allow-custom-prefix

Conversation

@RudyWeber
Copy link
Copy Markdown
Contributor

@RudyWeber RudyWeber commented Nov 17, 2020

Some tools such as create-react-app only expose specifically prefixed environment variables (for CRA, it's REACT_APP_) and do so only at build time. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime.

This is problematic when we need access to PLATFORM_* environment variables.
To do so, we need to be able to specify a custom prefix so we can pick up the re-exported relevant variables with the prefix.

Then we can do:

.platform.app.yaml

hooks:
  deploy: |
    set -e
    REACT_APP_PLATFORM_ROUTES=$PLATFORM_ROUTES \
    REACT_APP_PLATFORM_RELATIONSHIPS=$PLATFORM_RELATIONSHIPS \
    yarn build

somewhere.js

import { config as platformConfig } from "platformsh-config";

// use React-specific prefix
const config = platformConfig({ varPrefix: "REACT_APP_PLATFORM_" });
const {
  environmentVariables: { NODE_ENV },
  isDev = NODE_ENV === "development",
} = config;

const getApiUrl = () => {
  // using platform?
  if (config.hasRelationship("api")) {
    const { host, port } = config.credentials("api");

    // local dev with ssh tunnel
    if (isDev) {
      return `http://${host}:${port}`;
    }

    // prod, we need the api route url
    const url = Object.entries(config.routes()).find(
      ([, { upstream }]) => upstream === "api"
    )[0];

    return `${url}:${port}`;
  }

  // local dev with local server
  return `http://localhost:4000`;
};

@chadwcarlson
Copy link
Copy Markdown
Contributor

Please also add an entry for this to the changelog

Comment thread README.md
@RudyWeber RudyWeber force-pushed the allow-custom-prefix branch from 9a0c9e5 to 383c3e0 Compare February 3, 2021 17:30
@Crell Crell merged commit ca019ee into master Feb 5, 2021
@Crell Crell deleted the allow-custom-prefix branch February 5, 2021 19:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants