A
A
Alexander2021-07-27 14:48:49
React
Alexander, 2021-07-27 14:48:49

How to do NextJS authorization check?

I have an endpoint that is responsible for checking authorization, and returns a response.
How can I process it at the front, where in the application should I make a request for this endpoint, and what should be written to the dependency array in 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)
      })
  }, [])

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question