Skip to content
This repository was archived by the owner on Jun 24, 2025. It is now read-only.
This repository was archived by the owner on Jun 24, 2025. It is now read-only.

Make authenticated API calls #46

@amaury1093

Description

@amaury1093

Steps to reproduce

After authentication, I store the accessToken in my redux state (and after that redux-persist automatically stores it in localStorage).

What I want to achieve is: Make every feathers API call with the accessToken, if it's present in the redux state.

What I'm doing now:

export const app = feathers(); // + configure rest, hooks...

// Append accessToken in header if present.
// It would be better to take the accessToken from redux state,
// but for now we keep this solution (i.e. take directly from
// localStorage)
app.hooks({
  before: hook => {
    const item = window.localStorage.getItem('persist:myApp'); // This is where redux-persist saves the accessToken
    if (item) {
      const { auth } = JSON.parse(item);
      const { accessToken } = JSON.parse(auth);
      if (!accessToken) {
        return;
      }
      hook.params.headers = {
        Authorization: `Bearer ${accessToken}`,
        ...hook.params.headers
      };
      return hook;
    }
  }
});

So what I'm doing is, before each API request, retrieve the accessToken from the localStorage (and not from the in-memory store!).

Expected behavior

There should surely be a way to do this without retrieving localStorage and parsing JSON before each api request.

Actual behavior

Didn't find a clean way to pass state variables to the feathers app.

The only way I found is, on every api request, do

componentWillMount() {
  this.props.findUsers({ // findUsers dispatches feathersRedux.users.find
    headers: { Authorization: `Bearer ${this.props.auth.accessToken}` }
  })
}

But doing this on every method is not viable.

System configuration

Tell us about the applicable parts of your setup.

Module versions 2.1.0

NodeJS version: Not relevant

Operating System: Not relevant

Browser Version: Not relevant

React Native Version: Not relevant

Module Loader: Not relevant

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions