Reputation: 693
I try to follow the example from the doc, on how to set up baseQuery
for sending headers which in my case here for authentication
const baseQuery = fetchBaseQuery({
baseUrl: '/',
prepareHeaders: (headers, { getState }) => {
const token = (getState() as RootState).auth.token
// If we have a token set in the state, let's assume that we should be passing it.
if (token) {
headers.set('authorization', `Bearer ${token}`)
}
return headers
},
})
this is how I setup my getServerSideProps
export const getServerSideProps = wrapper.getServerSideProps(
store =>
async ({ locale, params }) => {
const slug = params?.slug;
if (typeof serviceProviderSlug === "string") {
store.dispatch(getOrders.initiate());
}
await Promise.all(getOrderRPOs());
return {
props: {
...(locale &&
(await serverSideTranslations(locale, ["common", "orders"]))),
},
};
}
);
I store my token in local storage with redux-persist
. when the page refreshes on the initial page, the store cannot read the token, and it will send the network request and the request sent will be in client-side rendering.
What did I do wrong? and how to set up the proper base query for server-side rendering.
Upvotes: 1
Views: 4334
Reputation: 153
To solve your problem you need to understand why we use next.js It took me a while to understand but the answer is you shouldn't or don't need to pass auth Token in SSR or SSG.
You might not know this but when you fetch data in normal react using useEffect() it first renders an empty div (or a loading page) and then after data is fetched it renders the page with data, So when SEO Bot crawls that page it indexes the empty page and not the one with data!.
To solve we use next.js SSR or SSG which pre-renders data on build or runtime, this makes our page with fetched Data crawlable by SEO bots.
SEO bot can never bypass authentication so if you are SSR or SSG to fetch data that require auth token then SEO will never be able to crawl it. Hence it is absolutely useless to complicate things and use SSR or SSG to fetch private data. So simply bypass the HYDRATION error and use Axios or SWR
Upvotes: 0
Reputation: 44166
I guess I answered this far already on Github, but since you asked here first I'll answer here as well:
Well, the Redux store is always empty on the server - SSR always uses a "new" Redux store for each request since technically there is no way the client could communicate the full store contents back to the server witch each request.
You can move data from the server store to the client store with each request (using the hydration options redux-next-wrapper offers), but never the other way round.
If you want something like a token shared between client and server, you would have to put that into a cookie and in prepareHeaders
access that cookie, not into your Redux store.
Upvotes: 3