Next js data fetching with axios instance and Authorization

Viewed 447

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: {},
  };
});
1 Answers

Server side rendered technology is a one-way street if you follow the standard practise. You won't get any local details - being it cookies, local store or local states back to the server.

I would let the server build the DOM as much as it makes sense (ie with empty user data) and let the client fetch the data via useEffect.

Related