I've just started learning next.js (TypeScript) and I've run into a problem.
I need to authorize a user to restore his session. The authorization key is a token that is stored in cookies. How to implement this task correctly?
At the moment, I have simply created a component in which I have embedded RootLayout
, and in the component itself I am already executing an API request to search for a user by token, but with this approach I get various errors. Perhaps there are some other options?
'use client';
import { fetcher } from '@/helpers/fetcher';
import { useUserStore } from '@/store/user';
import { QueryCache, useQuery } from '@tanstack/react-query';
import { deleteCookie, getCookie } from 'cookies-next';
import { useEffect } from 'react';
export default function Auth() {
const { user, setUser } = useUserStore();
const rememberToken = getCookie('remember_token');
if (user == null && rememberToken != null) {
const { isSuccess, data, } = useQuery({
queryKey: ['loginToken'],
queryFn: async () => await fetcher(process.env.API + '/auth/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
remember_token: rememberToken,
})
}),
})
if (isSuccess && data != null) {
const userData = data.user;
setUser({
id: userData.id,
rememberToken: userData.remember_token,
email: userData.email,
}, true);
} else deleteCookie('remember_token');
}
return <></>
}
P.s: The useUserStore
was created using zustand
to store global user information.
Comments
Post a Comment