Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use of deprecated webpack DevServer onBeforeSetupMiddleware and onAfterSetupMiddleware options #11860

Open
cduff opened this issue Dec 31, 2021 · 29 comments

Comments

@cduff
Copy link

cduff commented Dec 31, 2021

Steps to reproduce

npx create-react-app my-app
cd my-app
npm start

Unexpected output

(node:22848) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:22848) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.

My environment

  • create-react-app 5.0.0
  • node 16.13.1
  • Windows 10
@Valker-Vinicius
Copy link

Any update?

@cduff
Copy link
Author

cduff commented Jan 5, 2022

Any update?

Looks like there's a PR open for this now: #11862

@ramdaniAli
Copy link

any idea on how to fix this ?

@mehrbanian
Copy link

mehrbanian commented Jan 24, 2022

Still having this issue. (with node 16.13.2)
Edit: for anyone experiencing the same issue this might help.

@holub008
Copy link

  1. This is just a deprecation warning. Nothing is currently broken. Rolling back to react-scripts@4 is unnecessary at this point and likely not a good idea.
  2. The PR linked above (fix(webpackDevServer): fix deprecation warning #11862) should fix the underlying issue (using deprecated webpack API). When that PR is released (looks like it will be in 5.0.1), update react-scripts to that version. No more warning, and you're future-proofed!

@Meligy
Copy link

Meligy commented Apr 26, 2022

Is there a workaround that can be done with craco or something until it's fixed?

Just trying to reduce false errors so that I can spot real issues earlier.

Thanks a lot.

@sbaggott
Copy link

  1. This is just a deprecation warning. Nothing is currently broken. Rolling back to react-scripts@4 is unnecessary at this point and likely not a good idea.
  2. The PR linked above (fix(webpackDevServer): fix deprecation warning #11862) should fix the underlying issue (using deprecated webpack API). When that PR is released (looks like it will be in 5.0.1), update react-scripts to that version. No more warning, and you're future-proofed!

Actually, this breaks our app locally. It's not just acting as a warning it's acting as an error and preventing the dev server from running. We are using react-scripts 5.0.1 and the fix is still not implemented in that version.
@holub008 any idea when 5.0.2 will be released?

@Cezar04
Copy link

Cezar04 commented May 17, 2022

i had the same problem, i just changed the react-scripts from package.json to version 5.0.0. For hte moment it works

@holub008
Copy link

holub008 commented May 18, 2022

@sbaggott I'm not a maintainer, just an interested party. It does seem as though this is impacting a large number of users; Even more so if it's crashing the dev server (it was not crashing mine in 5.0.0, FWIW).

@sbaggott
Copy link

sbaggott commented May 23, 2022 via email

@mrwensveen
Copy link

mrwensveen commented May 23, 2022 via email

@luis-neira
Copy link

CRACO Solution

For anyone using CRACO and is trying to override the devServer config, in order to resolve the DeprecationWarning, here is the solution.

import fs from "fs";

import NodePolyfillPlugin from "node-polyfill-webpack-plugin";
import evalSourceMap from "react-dev-utils/evalSourceMapMiddleware";
import redirectServedPath from "react-dev-utils/redirectServedPathMiddleware";
import noopServiceWorker from "react-dev-utils/noopServiceWorkerMiddleware";

import type { CracoConfig } from "@craco/craco";

const config: CracoConfig = {
  webpack: {
    plugins: {
      add: [
        new NodePolyfillPlugin({
          excludeAliases: ["console"],
        }),
      ] /* An array of plugins */,
    },
  },
  devServer: (devServerConfig, { env, paths }) => {
    devServerConfig = {
      onBeforeSetupMiddleware: undefined,
      onAfterSetupMiddleware: undefined,
      setupMiddlewares: (middlewares, devServer) => {
        if (!devServer) {
          throw new Error("webpack-dev-server is not defined");
        }

        if (fs.existsSync(paths.proxySetup)) {
          require(paths.proxySetup)(devServer.app);
        }

        middlewares.push(
          evalSourceMap(devServer),
          redirectServedPath(paths.publicUrlOrPath),
          noopServiceWorker(paths.publicUrlOrPath)
        );

        return middlewares;
      },
    };
    return devServerConfig;
  },
};

export default config;

I hope this helps someone. Happy hacking : )

@chris-dyke
Copy link

The solution found here - https://stackoverflow.com/questions/70469717/cant-load-a-react-app-after-starting-server

Updating from

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(proxy('/proxypath', { target: '<target path>' }));
};

to

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(createProxyMiddleware('/proxypath', { target: '<target path>' }));
};

Has fixed this for me

@prince272
Copy link

Upgrade to npx create-react-app@5.0.1 my-app

@pankajuprety
Copy link

Any update?

Looks like there's a PR open for this now: #11862

What do you mean by PR

@morremeyer
Copy link

@pankajuprety PR is short for “Pull Request”. GitHub has pretty extensive documentation about PRs in https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests.

@26haroon26
Copy link

hey,
simple solution is here
In file: node_modules/react-scripts/config/webpackDevServer.config.js
like this

onBeforeSetupMiddleware(devServer) { // Keep evalSourceMapMiddleware// middlewares beforeredirectServedPath` otherwise will not have any effect
// This lets us fetch source contents from webpack for the error overlay
devServer.app.use(evalSourceMapMiddleware(devServer));

if (fs.existsSync(paths.proxySetup)) {
// This registers user provided middleware for proxy reasons
require(paths.proxySetup)(devServer.app);
}

},
onAfterSetupMiddleware(devServer) {
// Redirect to PUBLIC_URL or homepage from package.json if url not match
devServer.app.use(redirectServedPath(paths.publicUrlOrPath));

// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// We do this in development to avoid hitting the production cache if
// it used the same host and port.
// https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
devServer.app.use(noopServiceWorkerMiddleware(paths.publicUrlOrPath));

}`

change to

`setupMiddlewares: (middlewares, devServer) => {
if (!devServer) {
throw new Error('webpack-dev-server is not defined')
}

if (fs.existsSync(paths.proxySetup)) {
    require(paths.proxySetup)(devServer.app)
}

middlewares.push(
    evalSourceMapMiddleware(devServer),
    redirectServedPath(paths.publicUrlOrPath),
    noopServiceWorkerMiddleware(paths.publicUrlOrPath)
)

return middlewares;

}`

@ChromeQ
Copy link

ChromeQ commented Jan 4, 2023

It is not advised to change files in the node_modules folder as @26haroon26 suggests above. Any changes there will be destroyed once dependencies are installed which should be happening on a production build or CI to ensure your deps are "clean".

If and I stress if there is a need to update node_modules dependencies then the safer solution is to use patch-package. But this should be as limited as possible and when no other solution is possible, the better and longer term solution is to either open a PR with the changes or jump over to an existing PR and subscribe to it to get updates when it is merged.

In this case I do not believe patching the package is necessary, and there is already an open PR #11862 to fix this, and since it is only a deprecation warning it can probably be ignored until it is merged.
But if it is breaking your builds as some have suggested above then there are other solutions with craco as commented above or the same thing could probably be achieved using customize-cra. But the best solution is best to downgrade to v5.0.0 and wait for v5.0.2 as it is unlikely you require the fix in v5.0.1

@MikeMcC399
Copy link

@ChromeQ

  • PR fix(webpackDevServer): fix deprecation warning #11862, which you mention, was submitted over one year ago by @zhaomengfan, who has not been active in the PR since it was submitted and the PR currently fails CI tests. So the question is whether there is anybody who will actively sponsor the PR and clean it up so it can be merged?

@Havardmj
Copy link

Havardmj commented Apr 13, 2023

Have this craco config that I'm trying to override the current proxy problem. But It don't seems to be working. Anyone have a suggestion why it's not co-operating as intended? Thx :)

const CracoLessPlugin = require('craco-less');
const path = require('path');
const { EnvironmentPlugin } = require('webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const evalSourceMap = require('react-dev-utils/evalSourceMapMiddleware');
const redirectServedPath = require('react-dev-utils/redirectServedPathMiddleware');
const noopServiceWorker = require('react-dev-utils/noopServiceWorkerMiddleware');
const fs = require('fs-extra');

module.exports = {
    webpack: {
        plugins: [
            new BundleAnalyzerPlugin({
                analyzerMode: 'disabled',
                openAnalyzer: false,
            }),
            new EnvironmentPlugin({
                GIT_COMMIT_HASH: 'local-dev',
            }),
        ],
        alias: {
            '@': path.resolve(__dirname, 'src/'),
        },
    },
    devServer: (devServerConfig, { env, paths }) => {
        devServerConfig = {
            onBeforeSetupMiddleware: undefined,
            onAfterSetupMiddleware: undefined,

            setupMiddlewares: (middlewares, devServer) => {
                if (!devServer) {
                    throw new Error('webpack-dev-server is not defined');
                }
                if (fs.existsSync(paths.proxySetup)) {
                    require(paths.proxySetup)(devServer.app);
                }

                middlewares.push(
                    evalSourceMap(devServer),
                    redirectServedPath(paths.publicUrlOrPath),
                    noopServiceWorker(paths.publicUrlOrPath)
                );

                return middlewares;
            },
        };
        return devServerConfig;
    },
    plugins: [{ plugin: CracoLessPlugin }],
    eslint: {
        enable: true,
        mode: 'extends',
        configure: {
            extends: 'react-app',
            rules: {
                'react/jsx-pascal-case': 'off',
            },
        },
    },
    jest: {
        configure: {
            moduleNameMapper: {
                '^@/(.*)$': '<rootDir>/src/$1',
            },
        },
    },
};

@delacruzjames
Copy link

Any updates Solutions for this?

Options

  1. Aws S3
  2. Aws Amplify
  3. VercelApp

@u-zer1
Copy link

u-zer1 commented Jul 20, 2023

Any updates?

@MikeMcC399
Copy link

https://github.com/babel/babel-plugin-proposal-private-property-in-object is showing the following message, so if it is true that "the create-react-app project ... is not maintianed (sic) anymore", then it would be helpful if this statement appeared explicitly in this repository's README to avoid having to "read between the lines"!

One of your dependencies, babel-preset-react-app, is importing the
"@babel/plugin-proposal-private-property-in-object" package without
declaring it in its dependencies. This is currently working because
"@babel/plugin-proposal-private-property-in-object" is already in your
node_modules folder for unrelated reasons, but it may break at any time.

babel-preset-react-app is part of the create-react-app project, which
is not maintianed anymore. It is thus unlikely that this bug will ever
be fixed. If you are starting a new project, you may consider using
maintained alternatives such as Vite (https://vitejs.dev/) instead.

Add "@babel/plugin-proposal-private-property-in-object" to your
devDependencies to work around this error. This will make this message
go away.

@rathorer
Copy link

This is really bad, I am facing issue during our deployment phase. We have developed our app and when trying to deploy on azure, where its treating these warnings as error and the project is not working. Its failing to start.
Below is not feasible solution for us, as the new deployment will override the change:
https://stackoverflow.com/questions/70469717/cant-load-a-react-app-after-starting-server

If create-react-app is not maintained, then it should be mentioned in the documentation so people don't end up stuck in the middle.

@morremeyer
Copy link

@rathorer Unfortunately, the project is not only unmaintained, but has been completely abandoned.

There's no other choice right now than to migrate to another tool.

@holub008
Copy link

It's understandable if CRA is no longer being maintained. It's disappointing & unprofessional that maintainers haven't come forward to announce deprecation or intent to continue developing v5. There may be organizational factors impacting maintainers' ability to make such an announcement.

So it seems no one can come forward to tell you CRA is deprecated with certainty, but IMO any maintained project should be migrated. 2 years since a release, with downstream tools jumping major versions is a security & compatibility liability. NPM download data speaks to developer outlook on CRA:

Screenshot 2023-10-19 at 4 53 24 PM

I recently migrated off CRA to vite. It took a couple days on my enterprise-grade app but was straightforward with good documentation. Good luck!

@MikeMcC399
Copy link

@cduff
Copy link
Author

cduff commented Oct 19, 2023

I opened this issue in Dec 2021. FYI I've since migrated my SPA to Next.js using an approach like https://nextjs.org/docs/app/building-your-application/upgrading/from-vite.

Vite also looked like a good option, but I had other non-SPA projects using Next, so decided to standardise on it.

Everything is going well, and the DX is far superior to CRA. Full disclosure: there is one key issue I'm currently working around: vercel/next.js#56636.

@nktka
Copy link

nktka commented Mar 15, 2024

The solution found here - https://stackoverflow.com/questions/70469717/cant-load-a-react-app-after-starting-server

Updating from

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(proxy('/proxypath', { target: '<target path>' }));
};

to

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(createProxyMiddleware('/proxypath', { target: '<target path>' }));
};

Has fixed this for me

If anyone has react scripts silently failing with no errors, I did a reverse of this suggestion when migrating from react-scripts 4.0.3 to 5.0.1 and it worked! Just swap "to" and "from".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests