underfrankenwood
underfrankenwood

Reputation: 893

Hydrate with RTK Query does throw errors

I have a very simple component to display data from my local API (made with Nextjs API routes). Im using RTK Query to fetch the data:

const api = createApi({
  reducerPath: 'data',
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  extractRehydrationInfo(action, { reducerPath }) {
    if (action.type === HYDRATE) {
      return action.payload[reducerPath];
    }
  },
  endpoints: (builder) => ({
    getData: builder.query({
      query: () => '/data',
    }),
  }),
});

But I also want to support SSR so the data is fetched on the server side and hydrated with client side. Im following example from: https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering

export const getServerSideProps = wrapper.getServerSideProps((store) => async () => {
  store.dispatch(api.endpoints.getData.initiate());
  await Promise.all(store.dispatch(api.util.getRunningQueriesThunk()));

  return {
    props: {},
  };
});

However, my app when using getServerSideProps starts to work unexpectedly. SSR throws error in the console:

An unhandled error occurred processing a request for the endpoint "getData". In the case of an unhandled error, no tags will be "provided" or "invalidated". TypeError: Failed to parse URL from /api/data

input: '/api/data', code: 'ERR_INVALID_URL'

Also everything else works pretty bad when using getServerSideProps enabled. The data mutation fails and caching too.

When refreshed, there's a flicker between SSR error in app and the app rendered on the client side. What could be the problem?

Upvotes: 0

Views: 984

Answers (1)

phry
phry

Reputation: 44226

While you can use urls like /foo in your browser, on the server that just doesn't work. In the browser, they are relative to the domain of the current website - but the server has no address bar with a domain in it.

Use a full url like https://example.com/foo ass your baseUrl.

Upvotes: 0

Related Questions