Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Advanced

Custom Middleware

Definition

Creating your own middleware function to intercept actions and add custom logic to the Redux pipeline.

Explain Like I'm New

You can write your own 'Bouncer'. To write a custom middleware, you have to write a weird function that returns a function that returns a function (Currying). It gives you ultimate power over everything happening in your app.

Real World Example

Writing a 'Profanity Filter' middleware. It intercepts every `SEND_MESSAGE` action, scans the payload text for bad words, replaces them with asterisks (`***`), and THEN passes the cleaned action to the reducer.

Common Use Cases

  • •Custom analytics
  • •Feature flags
  • •Data sanitization

Interactive Example

// A custom middleware that blocks actions if the user isn't an Admin

const adminCheckMiddleware = storeAPI => next => action => {
  // 1. Check if the action requires admin rights
  if (action.type === 'DELETE_DATABASE') {
    
    // 2. Check the current state to see who the user is
    const state = storeAPI.getState();
    
    if (state.user.role !== 'ADMIN') {
      // 3. BLOCK THE ACTION! (We never call next())
      console.error('Access Denied!');
      return; 
    }
  }

  // 4. Pass the action along normally if everything is okay
  return next(action);
};

Interview Questions

basic

  • What is the signature structure of a Redux middleware function?

intermediate

  • What must a custom middleware call to pass the action to the next step?

Flash Cards

Question

Signature structure?

Click to reveal answer
Answer

`store => next => action => { ... }` (This pattern is called Currying).

Question

What must it call?

Click to reveal answer
Answer

It MUST call `next(action)`. If you forget this, your entire app will freeze because the action never reaches the reducer.