Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
axois react-keycloak/web token in inteceptor

I'm trying to use a request inteceptor with react-keycloak/web - however i get an array of errors when doing so.

import axios from 'axios';
import { useKeycloak } from '@react-keycloak/web';

const { keycloak } = useKeycloak();

const instance = axios.create({
  baseURL: 'https://example.com/api/v1/',
  timeout: 30000,
});

instance.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `${keycloak.token}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

but i get:

React Hook "useKeycloak" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks

Now i have of course tried to create a function with for example GetToken():

function GetToken() {
  const { keycloak } = useKeycloak();
  return keycloak.token
}

but doing so leaves me with:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

What am i doing wrong here?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can't use react hooks out of react tree.

You can export axoios instance and import it elsewhere inside react (eg: App.js) and set interceptors there.

for example:

import axiosIns from 'api';
import { useKeycloak } from '@react-keycloak/web';
import { useEffect } from "react";
import WholeApp from "WholeApp";

const App = () => {
    const { keycloak } = useKeycloak();

    useEffect(() => {
        axiosIns.interceptors.request.use(
            (config) => {
                config.headers.Authorization = `${keycloak.token}`;
                return config;
            },
            (error) => {
                return Promise.reject(error);
            }
        );
    }, []);

    return <WholeApp />;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!