josx / ra-data-feathers

A feathers rest client for react-admin
MIT License
157 stars 53 forks source link

How to add custom headers? #181

Closed strarsis closed 2 years ago

strarsis commented 2 years ago

How can custom request headers be added? The ra-data-feathers REST client is a function that can be called with type, resource and params, but where can the HTTP headers be changed?

strarsis commented 2 years ago

The underlying Feathers instance offers hooks that can be used to change/add HTTP headers:

const feathersApp = feathers();

// [...]

feathersApp.configure((app: Application) => {
  app.hooks({
    before: {
      all: [
        hook => {
          if (!hook.params.headers) {
            hook.params.headers = {};
          }
          hook.params.headers['x-client'] = 'react-admin';
        }
      ]
    }
  })
});

// [...]

import { authClient, restClient } from 'ra-data-feathers';
// [...]
const dataProvider = restClient(feathersClient, restClientOptions);

In some cases this custom header (X-Client) must be allowed by the server by sending its header name (CORS). (Note: The RFC user agent header can't be changed in current browsers by the way). FeathersJS server / backend:

// Allow `X-Client` custom HTTP request header from clients (CORS)
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Headers', 'x-client');
  next();
});