Blog>
Snippets

Setting Up Middleware in Redux Toolkit 2.0

Demonstrate the updated way to include custom middleware in your Redux store when bootstrapping with Redux Toolkit 2.0.
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './rootReducer';

// Define your custom middleware
const customMiddleware = store => next => action => {
    // Custom middleware logic
    console.log('Middleware triggered:', action);
    return next(action);
};

// Configure the store and include the custom middleware
const store = configureStore({
    reducer: rootReducer,
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(customMiddleware),
});

export default store;
This JavaScript code represents the setup of a Redux store using Redux Toolkit 2.0, including a custom middleware. It imports the necessary functions from @reduxjs/toolkit, defines a custom middleware that logs all actions, and then includes it in the store configuration by concatenating it with the default middlewares.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Redux Toolkit 2.0 Middleware Setup</title>
    <script src="path/to/your/bundled/store.js" defer></script>
    <!-- Add other scripts here -->
</head>
<body>
    <div id="app">
        <!-- Your App's Content -->
    </div>
</body>
</html>
This HTML code represents a basic HTML structure for a web page that would use the Redux store including custom middleware set up in the previous JavaScript code snippet. The JavaScript file that sets up and exports the Redux store (including the middleware) is linked as a deferred script.
body {
    font-family: 'Arial', sans-serif;
}

#app {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    text-align: center;
}
This is a simple CSS snippet that styles the basic layout of the application. It sets a global font and aligns the app's content to the center, with a maximum width and padding.