axrising
@axrising

Как сделать проверку авторизации NextJS?

У меня есть эндпоинт который отвечает за проверку авторизации, и возвращает ответ.
Как я могу обработать его на фронте, в каком месте приложения делать запрос на этот эндпоинт, и что нужно записать в массив зависимостей в useEffect?
import { NextApiRequest, NextApiResponse } from 'next'
const jwt = require('jsonwebtoken')

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'GET') {
    if (!('token' in req.cookies)) {
      res.status(401).json({ message: 'Unable to auth' })
      return
    }
    let decoded
    const token = req.cookies.token
    if (token) {
      try {
        decoded = jwt.verify(token, process.env.JWT_SECRET)
      } catch (e) {
        console.error(e)
      }
    }

    if (decoded) {
      res.status(200).json({ decoded, status: 'Авторизаци выполнена успешно!' })
      return
    } else {
      res.status(401).json({ message: 'Unable to auth' })
    }
  }
}


React.useEffect(() => {
    fetch('/api/me', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })
      .then((res) => res.json())
      .then((data) => {
        if (data && data.error) {
          setAuthError(data.message)
        }
        if (data && data.status) {
          setAuthError('')
          setAuth(true)
          toast.success(data.status)
        }
      })
      .catch((error) => {
        toast.error('Произошла ошибка :(')
        console.log(error)
      })
  }, [])
  • Вопрос задан
  • 161 просмотр
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы