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

240
Vistas
Next js data fetching with axios instance and Authorization

I'm using NextJS 12.0.10 with next-redux-wrapper 7.0.5 And Axios custom instance to hold user JWT token saved in local storage and inject it with every request also to interceptors incoming error's in each response

The problem with this is that I simply cannot use the Axios instance inside the Next data fetching methods

Because there is no way to bring user JWT Token from local storage when invoking the request inside the server Also, I cannot track the request in case of failure and send the refresh token quickly

I tried to use cookies but getStaticProps don't provide the req or resp obj Should I use getServerSideProps always


axios.js

  const axiosInstance = axios.create({
    baseURL: baseURL,
    timeout: 20000,
    headers: {
      common: {
        Authorization: !isServer()
          ? localStorage.getItem("access_token")
            ? "JWT " + localStorage.getItem("access_token")
            : null
          : null,
        accept: "application/json",
      },
    },
  });

login-slice.js

  export const getCurrentUser = createAsyncThunk(
    "auth/getCurrentUser",
    async (_, thunkApi) => {
      try {
        const response = await axiosInstance.get("api/auth/user/");
        await thunkApi.dispatch(setCurrentUser(response.data));
        return response.data;
      } catch (error) {
        if (error.response.data) {
          return thunkApi.rejectWithValue(error.response.data);
        }
        toast.error(error.message);
  
        return thunkApi.rejectWithValue(error.message);
      }
    }
  );

Page.jsx

export const getStaticProps = wrapper.getStaticProps((store) => async (ctx) => {
  try {
    await store.dispatch(getCurrentUser());
  } catch (e) {
    console.log("here", e);
  }

  return {
    props: {},
  };
});
about 4 years ago · Juan Pablo Isaza
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