Lukas Safari
Lukas Safari

Reputation: 1968

Add react middleware when not in production

The question is simple,

How I can add a react or redux middle-ware (like Logger) when not in production.

I don't want users be able to see the logging info in the console tab.

Upvotes: 0

Views: 1231

Answers (2)

Mehdi Dehghani
Mehdi Dehghani

Reputation: 11601

Let say you have 2 middlewares, logger and thunk and you want to add logger when you are not in production, you can do that using following code:

const middleware = [thunk];
if (process.env.NODE_ENV !== 'production') {
    middleware.push(logger);
}

And you can set NODE_ENV to production using following code:

set NODE_ENV=production

Or using PowerShell:

$env:NODE_ENV="production"

Set within package.json (you need to install cross-env, more info right here: How to set Environment variables from within package.json [Node.js]):

"scripts": {    
    "build": "cross-env NODE_ENV=production webpack -p"
}

Upvotes: 3

Krasimir
Krasimir

Reputation: 13529

There is no a Redux way to do this. It is up to you to implement this logic. You may use the window.location.origin to get an idea of where you app runs. If it runs on localhost or your staging environment then you should not add the logger. Of course if you server-side render you have to check if window is available. If not I guess is fine to add the logger. Check out how it is done in redux-devtools https://github.com/zalmoxisus/redux-devtools-extension/blob/master/npm-package/developmentOnly.js#L7

Upvotes: 0

Related Questions