Answer the question
In order to leave comments, you need to log in
Next.js - How to solve the problem with the authorization check during page rendering?
In getStaticProps , I make a request to /api, which subsequently sends a jwt from the cookie to the server to check authorization (it does not happen on the client). When I make a request from useEffect(), there are no problems, but in the case of getStaticProps, this appears:
pages/auth/index.tsx
const AuthContainer = () => {
const dispatch = useDispatch()
const { isAuth, error } = useSelector((state: AppType) => state.auth)
const loginUser = (usersData: userLogin): setAuthActionType => dispatch({type: authTypes.SET_AUTH, payload: usersData})
const registationUser = (userData: userRegistation): registationUserType => dispatch({ type: authTypes.REGISTATION_USER, payload: userData })
return (
<>
<HeadComponent title="Добро пожаловать в MyOcean Education !" />
<Auth
loginUser={loginUser} registrationUser={registationUser}
isAuth={isAuth} error={error}
/>
</>
)
};
export async function getStaticProps(ctx) {
let res = await axios.get("/pupil/api/checkauth")
if (res.data.isAuth) return {redirect: { destination: "/root", permament: false }}
return {props: { foo: "bar" }}
}
export default AuthContainer;
import { serverAxiosConfig } from './../../store/api/users';
import { NextApiResponse, NextApiRequest } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
let isAuth = await serverAxiosConfig.get("/auth/check", {headers: {"Authorization": "Bearer " + req.cookies["jwt"]}})
res.json({...isAuth.data, isAuth: true})
} catch (error) {
res.json(error)
}
}
export const serverAxiosConfig = axios.create({ baseURL: "http://localhost:5000/api" })
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question