I
I
IFramex2021-02-22 22:59:12
typescript
IFramex, 2021-02-22 22:59:12

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:

60340b99a0e66590000812.png

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;


pages/api/checkauth.tsx
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)
  }
}

serverAxiosConfig
export const serverAxiosConfig = axios.create({ baseURL: "http://localhost:5000/api" })

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valery, 2021-02-22
@IFraim

https://nextjs.org/docs/basic-features/data-fetching
60340e653446a510630900.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question