deep-jade
deep-jade3d ago

Passing authorization token to swizzled simple-rest data provider

How do I passing authorization bearer token to a swizzled simple-rest data provider
2 Replies
kapa.ai
kapa.ai3d ago
Hi @NIHR. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To pass an authorization bearer token to a swizzled (customized) simple-rest data provider in Refine, you should create a custom Axios instance that attaches the token to every request, and then provide this instance to your (swizzled) data provider. Here's how you can do it: 1. Create an Axios instance and set up an interceptor to add the token:
import axios from "axios";

const axiosInstance = axios.create();

axiosInstance.interceptors.request.use(
(config) => {
const token = localStorage.getItem("token");
if (token && config.headers) {
config.headers["Authorization"] = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
import axios from "axios";

const axiosInstance = axios.create();

axiosInstance.interceptors.request.use(
(config) => {
const token = localStorage.getItem("token");
if (token && config.headers) {
config.headers["Authorization"] = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
2. Pass this Axios instance to your swizzled data provider: If you have swizzled (customized) the simple-rest data provider (e.g., after running npm run refine swizzle and editing your provider), you can use it like this:
import { Refine } from "@refinedev/core";
import { dataProvider } from "./rest-data-provider"; // your swizzled provider

const API_URL = "<https://api.example.com";>

const App = () => (
<Refine
dataProvider={dataProvider(API_URL, axiosInstance)}
// ...other props
/>
);
import { Refine } from "@refinedev/core";
import { dataProvider } from "./rest-data-provider"; // your swizzled provider

const API_URL = "<https://api.example.com";>

const App = () => (
<Refine
dataProvider={dataProvider(API_URL, axiosInstance)}
// ...other props
/>
);
This approach ensures that the authorization token is included in the headers of every request made by your (swizzled) simple-rest data provider. This method is recommended in both the official documentation and community discussions for handling authentication with custom or swizzled data providers in Refine Simple REST data provider docs Github Issue #4622. If you need to further customize request logic (e.g., add more headers or handle cookies), you can continue to modify your swizzled data provider as needed. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3d ago
<@310660428135006208> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?