Reputation: 2949
I'm using RTK Query for the first time, and I want to keep the user logged in when refresh the page.
I'm dealing with an endpoint that doesn't expire the access token (it lasts for a year or so), so there's no refresh token to use or anything, just the access token (I know, it sucks for security, but I can't do anything about it).
So, do I store the access token in a localStorage or a Cookie? I know that's not recommended, but I don't know what to do.
Any help or a link to a guide is appreciated.
And here's my authApiSlice code ...
import { MetadataObj } from '../../../types/globalTypes';
import { apiSlice } from '../../app/api/apiSlice';
import { logOut } from './authSlice';
export const authApiSlice = apiSlice.injectEndpoints({
endpoints: builder => ({
login: builder.mutation({
query: (credentials: MetadataObj) => ({
url: "/signin",
method: "POST",
body: { ...credentials },
}),
}),
sendLogout: builder.mutation({
query: () => ({
url: "/logout",
method: "POST",
}),
async onQueryStarted(arg, { dispatch, queryFulfilled }) {
try {
await queryFulfilled;
dispatch(logOut(null));
dispatch(apiSlice.util.resetApiState());
} catch (err) {
console.log(err);
}
},
}),
}),
});
export const { useLoginMutation, useSendLogoutMutation } = authApiSlice;
Upvotes: 0
Views: 3931
Reputation: 220
In general, you have two options:
store access token in (local storage/cookie) and read from there whenever you need it.
store access token in redux and persist that redux state!
as you know redux states will not persist and when you refresh page your redux will be empty at next time. for second apporoach you have to setup redux-persist within your redux store and integrate with toolkit (redux toolkit persist document).
this also can help: How to configure redux-persist with redux-toolkit?
by the way, I prefer the first approach.
Upvotes: 1