Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda