question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Issues with CRA PUBLIC_URL environment variable specified

See original GitHub issue

Environment

Name Version
msw 0.26.1
browser Chrome 88 / Firefox 85
OS Linux / Windows

Request handlers

I pulled the request handlers directly from both the example code and the main msw GitHub page.

import { setupWorker, rest } from 'msw';

// Start the mocking conditionally.
if (process.env.NODE_ENV === 'development') {
  const worker = setupWorker(
    rest.post('/login', (req, res, ctx) => {
      const { username } = req.body;

      return res(
        ctx.json({
          id: 'f79e82e8-c34a-4dc7-a49e-9fadc0979fda',
          username,
          firstName: 'John',
          lastName: 'Maverick',
        })
      );
    }),
    rest.get('https://github.com/octocat', (req, res, ctx) => {
      return res(
        ctx.delay(1500),
        ctx.status(202, 'Mocked status'),
        ctx.json({
          message: 'Mocked response JSON body',
        })
      );
    })
  );
  worker.start({
    serviceWorker: {
      url: `${process.env.PUBLIC_URL}/mockServiceWorker.js`,
    },
  });

  window.worker = worker;
}

Actual request

The following were inserted within the examples’s LoginForm.js:

// In order to test the first handler
const handleFormSubmit = useCallback(
  (event) => {
    // Prevent the default behavior, as we don't want
    // for our page to reload upon submit.
    event.preventDefault();

    // Perform a POST /login request and send the username
    fetch('/login', {
      method: 'POST',
      body: JSON.stringify({
        username,
      }),
    })
      .then((res) => res.json())
      // Update the state with the received response
      .then(setUserData);
  },
  [username]
);

// In order to test the second handler
  useEffect(() => {
    fetch('https://github.com/octocat')
      .then((res) => res.json())
      .then((value) => console.log('value: ', value));
  }, []);

Current behavior

When we have the PUBLIC_URL environment variable set within .env like so:

PUBLIC_URL=/relative-test-path

Both handlers are shown as registered properly:

Both handlers properly registered

When attempting to test the first (POST) handler, which is pulled directly from the example, we see that the the handler is not respected (even if we change the URL explicitly to “http://localhost:3001/login” or “http://localhost:3001/relative-test-path/login”), as CRA takes over and redirects:

First handler

When attempting to test the second handlers (which is fired on page load, a simple GET request as shown in the main msw usage example), we can see the handler is not respected as we receive a CORS error:

Second handler

Network tools CORS Error

Expected behavior

As soon as we remove the PUBLIC_URL from .env and restart CRA, everything works as expected–both handlers work properly:

Working properly

Screenshots

See above.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
Justinohallocommented, Feb 6, 2021

@kettanaito I think the suggestion above would be a decent addition to the MSW docs. I found it to be much easier given that my setup only uses the homepage / PUBLIC_URL in production.

1reaction
Justinohallocommented, Feb 6, 2021

What is the purpose of your PUBLIC_URL ? If it is for production, put it into an .env.production file at the root of your directory and remove it from the .env file. https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env

I had the exact same issue, but we only used our PUBLIC_URL for production so it may not fit your use case.

Alternatively, you can try something like this if you want to move your PUBLIC_URL into your package.json : https://mswjs.io/docs/getting-started/integrate/browser#using-homepage-property-in-packagejson

However, I was not able to get the package.json approach to work.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to set PUBLIC_URL in create-react-app? - Stack Overflow
Here is my experience on this issue: create-react-app or CRA system sets the. %PUBLIC_URL%. variable from .env file in the root of the ......
Read more >
Configure the create-react-app public URL post-build with ...
For a project, I had the requirement of making the public URL of the application configurable via an environment variable that can be...
Read more >
Handling runtime environment variables in create-react-apps
A new package called runtime-env-cra allows you to handle environment variables in quick and easy way with create-react-apps.
Read more >
Public Path - webpack
It allows you to specify the base path for all the assets within your application. Use Cases. There are a few use cases...
Read more >
How to implement runtime environment variables with create ...
env file with our first environment variable that we want to expose. # Generate React App create-react-app cra-runtime-environment-variables cd ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found