Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda