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

233
Views
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
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!