How can I manage authentication in next 13.4 with external api with redux toolkit?
Unanswered
Najmus Sakib posted this in #help-forum
I am implementing authentication with next 13.4 app dir with redux toolkit as a state management, I am using django as my backend api endpoint and sending session with jwt token. I am calling getMe api to get currently logged in user if they sent jwt with request. and want to store the response(current user) for later uses so I don't have to call getMe over and over again and I am dispatching a redux action for storing the result on my store. based on store data I am showing a user is logged in or not. But the problem is store data is globally persisted on server, How can i make that per user session so I can check a user is logged in or not only for hard page reload .
Root layout.tsx
store.ts
Root layout.tsx
export default async function RootLayout({
children,
}: {
children: React.ReactNode
}) {
const cookiesList = cookies().getAll()
const user = await getMe(cookiesList)
if (user) {
store.dispatch(setUser(user))
}
return (
<html lang="en">
<body className='rbt-header-sticky'>
<Providers preloadedState={{
auth: {
user: user
}
}}> {/* redux toolkit provider */}
<Header />
<MobileMenu />
{children}
</Providers>
</body>
</html>
)
} store.ts
import userReducer from '@/components/Auth/authSlice';
import { configureStore } from '@reduxjs/toolkit'
export const createStore = (preloadedState = {}) => {
return configureStore({
reducer: {
auth: userReducer
},
devTools: process.env.NODE_ENV !== 'production',
preloadedState
})
}
const store = createStore();
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch
export default store;