RTKQuery SSR custom auth headers.
See original GitHub issueHello 😃
I’m trying to work out the best approach to using RTKQuery with SSR and auth cookies/headers.
At the moment we are using cookies for our auth, which means that in a browser environment (client side) every fetch request automatically attaches the cookies and auth succeeds.
On the server side, this is a little more tricky. We can access the cookies in next.js via the server side context prop. (eg ctx.req.headers
), but then I’m not sure how this cookie header can be passed into rtkquery.
I can think of one option:
We can insert cookie data into the redux store on the server side and then in the prepareHeaders
function we can access the store with getState()
and set a cookie header - This way we only have the auth logic in one place, but I am weary about inserting cookie creds into the store. I guess I could dispatch an action afterwards to remove the cookies so they aren’t hydrated to the client side… but it sounds messy.
Is there a more established way of achieving this or does this sound right?
Issue Analytics
- State:
- Created a year ago
- Comments:9 (3 by maintainers)
Yup, that’s my suggestion.
extra
will not be hydrated, only the state.Thanks for the reply @phryneas - this approach sounds really promising. Just to confirm, are you suggesting to add to the extraArgument via genDefaultMiddleware https://redux-toolkit.js.org/api/getDefaultMiddleware and then consume that extra inside prepareHeaders? That sounds like it will work well (assuming extra is not hydrated to the client side).