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

Request middleware #120

Closed
samuelcastro opened this issue Nov 15, 2018 · 2 comments
Closed

Request middleware #120

samuelcastro opened this issue Nov 15, 2018 · 2 comments

Comments

@samuelcastro
Copy link

samuelcastro commented Nov 15, 2018

How to build up a redux middleware that would intercept the request headers before it goes out, for example, to automatically include an authentication JWT in the http header.

I know that there is discussion about it here #3 and here #31, but honestly it's not clear how this could be implemented with redux-query.

Thanks.

@trashstack
Copy link
Contributor

Hi @samuelcastro,

If you wanted to add a header like Authorization: Bearer abc123 to a single request you can do so by adding it to the options in the query config e.g.

const jwtToken = 'abc123';
const queryConfig = {
  url: '/some-jwt-secured-endpoint',
  options: {
    headers: {
      authorization: `Bearer ${jwtToken}`,
    },
  },
};
dispatch(requestAsync(queryConfig));

In order to do this for every request you can apply a middleware to redux. It could look something like this:

import { actionTypes } from 'redux-query';

const { MUTATE_ASYNC, REQUEST_ASYNC } = actionTypes;
const jwtToken = 'abc123';

const jwtMiddleware = store => next => action => {
  if (action && (action.type === MUTATE_ASYNC || action.type === REQUEST_ASYNC)) {
    // This is a redux-query action so add the JWT header
    const options = action.options || {};
    const headers = options.headers || {};
    const updatedAction = {
      ...action,
      options: {
        ...options,
        headers: {
          ...headers,
          authorization: `Bearer ${jwtToken}`,
      },
    };
    
    // Let the action continue, but now with the JWT header.
    next(updatedAction);
  } else {
    // This isn't a redux-query action so just let it pass through
    next(action);
  }
};

@samuelcastro
Copy link
Author

@ManThursday Thanks, that's exactly what I need!

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

No branches or pull requests

2 participants