Can't build create-react-app project with custom PUBLIC_URL

JavascriptReactjsCreate React-App

Javascript Problem Overview


I'm trying

PUBLIC_URL=http://example.com npm run build

with a project built using the latest create-react-script.

However, the occurrences of %PUBLIC_URL% in public/index.html are replaced with an empty string, not the expected value PUBLIC_URL.

public/index.html contains code like

<script src="%PUBLIC_URL%/static/js/jarvis.widget.min.js"></script>

Hours of searching the internet and stack overflow show that very little is written about PUBLIC_URL. I cloned create-react-app from GitHub and have been browsing the code but have not yet been enlightened.

Does anyone have any suggestions as to what I'm doing wrong?

Javascript Solutions


Solution 1 - Javascript

If the other answers aren't working for you, there's also a homepage field in package.json. After running npm run build you should get a message like the following:

The project was built assuming it is hosted at the server root.
To override this, specify the homepage in your package.json.
For example, add this to build it for GitHub Pages:

  "homepage" : "http://myname.github.io/myapp",

You would just add it as one of the root fields in package.json, e.g.

{
  // ...
  "scripts": {
    // ...
  },
  "homepage": "https://example.com"
}

When it's successfully set, either via homepage or PUBLIC_URL, you should instead get a message like this:

The project was built assuming it is hosted at https://example.com.
You can control this with the homepage field in your package.json.

Solution 2 - Javascript

People like me who are looking for something like this in in build:

<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">

Then setting https://dsomething.cloudfront.net to homepage in package.json will not work.

1. Quick Solution

Build your project like this:
(windows)

set PUBLIC_URL=https://dsomething.cloudfront.net&&npm run build

(linux/mac)

PUBLIC_URL=https://dsomething.cloudfront.net npm run build

And you will get

<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">

in your built index.html

Create a file called .env at your project root(same place where package.json is located).
In this file write this(no quotes around the url):

PUBLIC_URL=https://dsomething.cloudfront.net

Build your project as usual (npm run build)
This will also generate index.html with:

<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">
3. Weird Solution (Will do not work in latest react-scripts version)

Add this in your package.json
"homepage": "http://://dsomething.cloudfront.net",

Then index.html will be generated with:

<script type="text/javascript" src="//dsomething.cloudfront.net/static/js/main.ec7f8972.js">

Which is basically the same as:

<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">

in my understanding.

Github Issue Github Comment

Solution 3 - Javascript

That is not how the PUBLIC_URL variable is used. According to the documentation, you can use the PUBLIC_URL in your HTML:

<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">

Or in your JavaScript:

render() {
  // Note: this is an escape hatch and should be used sparingly!
  // Normally we recommend using `import` for getting asset URLs
  // as described in “Adding Images and Fonts” above this section.
  return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
}

The PUBLIC_URL is not something you set to a value of your choosing, it is a way to store files in your deployment outside of Webpack's build system.

To view this, run your CRA app and add this to the src/index.js file:

console.log('public url: ', process.env.PUBLIC_URL)

You'll see the URL already exists.

Read more in the CRA docs.

Solution 4 - Javascript

Actually the way of setting environment variables is different between different Operating System.

Windows (cmd.exe)

set PUBLIC_URL=http://xxxx.com&&npm start

(Note: the lack of whitespace is intentional.)

Linux, macOS (Bash)

 PUBLIC_URL=http://xxxx.com npm start
{
  "scripts": {
    "serve": "cross-env PUBLIC_URL=http://xxxx.com npm start"
  }
}

ref: create-react-app/README.md#adding-temporary-environment-variables-in-your-shell at master · facebookincubator/create-react-app

Solution 5 - Javascript

Have a look at the documentation. You can have a .env file which picks up the PUBLIC_URL

Although you should remember that what its used for -

> You may use this variable to force assets to be referenced verbatim to > the url you provide (hostname included). This may be particularly > useful when using a CDN to host your application.

Solution 6 - Javascript

If you see there source code they check if process.env.NODE_ENV === 'development' returns true, and they automatically removes host URL and only return path.

For example, if you set like below

PUBLIC_URL=http://example.com/static/

They will remove http://example.com and only return /static.

However since you only set root URL like http://example.com, they will just return an empty string since there no subpath in your URL string.

This only happens if you call react-scripts start, and if you call react-scripts build then isEnvDevelopment will be false, so it will just return http://example.com as what you set in the .env file.

Here is the source code of getPublicUrlOrPath.js.

/**
 * Returns a URL or a path with slash at the end
 * In production can be URL, abolute path, relative path
 * In development always will be an absolute path
 * In development can use `path` module functions for operations
 *
 * @param {boolean} isEnvDevelopment
 * @param {(string|undefined)} homepage a valid url or pathname
 * @param {(string|undefined)} envPublicUrl a valid url or pathname
 * @returns {string}
 */
function getPublicUrlOrPath(isEnvDevelopment, homepage, envPublicUrl) {
  const stubDomain = 'https://create-react-app.dev';

  if (envPublicUrl) {
    // ensure last slash exists
    envPublicUrl = envPublicUrl.endsWith('/')
      ? envPublicUrl
      : envPublicUrl + '/';

    // validate if `envPublicUrl` is a URL or path like
    // `stubDomain` is ignored if `envPublicUrl` contains a domain
    const validPublicUrl = new URL(envPublicUrl, stubDomain);

    return isEnvDevelopment
      ? envPublicUrl.startsWith('.')
        ? '/'
        : validPublicUrl.pathname
      : // Some apps do not use client-side routing with pushState.
        // For these, "homepage" can be set to "." to enable relative asset paths.
        envPublicUrl;
  }

  if (homepage) {
    // strip last slash if exists
    homepage = homepage.endsWith('/') ? homepage : homepage + '/';

    // validate if `homepage` is a URL or path like and use just pathname
    const validHomepagePathname = new URL(homepage, stubDomain).pathname;
    return isEnvDevelopment
      ? homepage.startsWith('.')
        ? '/'
        : validHomepagePathname
      : // Some apps do not use client-side routing with pushState.
      // For these, "homepage" can be set to "." to enable relative asset paths.
      homepage.startsWith('.')
      ? homepage
      : validHomepagePathname;
  }

  return '/';
}

Solution 7 - Javascript

Not sure why you aren't able to set it. In the source, PUBLIC_URL takes precedence over homepage

const envPublicUrl = process.env.PUBLIC_URL;
...
const getPublicUrl = appPackageJson =>
  envPublicUrl || require(appPackageJson).homepage;

You can try setting breakpoints in their code to see what logic is overriding your environment variable.

Solution 8 - Javascript

As documented here create-react-app will only import environment variables beginning with REACT_APP_, so the PUBLIC_URL, I believe, as mentioned by @redbmk, comes from the homepage setting in the package.json file.

Solution 9 - Javascript

This problem becomes apparent when you try to host a react app in github pages.

How I fixed this,

In in my main application file, called app.tsx, where I include the router. I set the basename, eg, <BrowserRouter basename="/Seans-TypeScript-ReactJS-Redux-Boilerplate/">

Note that it is a relative url, this completely simplifies the ability to run locally and hosted. The basename value, matches the repository title on GitHub. This is the path that GitHub pages will auto create.

That is all I needed to do.

See working example hosted on GitHub pages at

https://sean-bradley.github.io/Seans-TypeScript-ReactJS-Redux-Boilerplate/

Solution 10 - Javascript

This solution works on a Linux bash command line:

  1. Go to your react project root directory.
  2. open the bash terminal on that directory.
  3. After that run below two commands and you will see that the PUBLIC_URL changed:
> export PUBLIC_URL=https://example.com
> npm run build

Solution 11 - Javascript

If the PUBLIC_URL environment variable has no effect, it may be due to this issue, which causes PUBLIC_URL to be ignored in development. It was fixed in create-react-app version 3.4.0.

Solution 12 - Javascript

If your app has routing, try like below

  1. Create a file called .env at your project root where package.json is located, then add your production URL like below

    PUBLIC_URL=https://something.com
    
  2. add basename to BrowserRouter in the route configure (in App.js/ App.jsx)

    <BrowserRouter basename="https://something.com">
    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGulliver SmithView Question on Stackoverflow
Solution 1 - JavascriptredbmkView Answer on Stackoverflow
Solution 2 - JavascriptVaibhav VishalView Answer on Stackoverflow
Solution 3 - JavascriptTobyView Answer on Stackoverflow
Solution 4 - JavascriptJimmyLvView Answer on Stackoverflow
Solution 5 - JavascriptDaveView Answer on Stackoverflow
Solution 6 - JavascriptwonsucView Answer on Stackoverflow
Solution 7 - JavascriptdosentmatterView Answer on Stackoverflow
Solution 8 - JavascriptTobyGView Answer on Stackoverflow
Solution 9 - JavascriptSean BradleyView Answer on Stackoverflow
Solution 10 - JavascriptMD JULHAS HOSSAINView Answer on Stackoverflow
Solution 11 - JavascriptGrant ZvolskyView Answer on Stackoverflow
Solution 12 - JavascriptGopala raja naikaView Answer on Stackoverflow