Facing 401 Unauthorized Error During Login in Laravel and Next.js App using NextAuth and SWR

127 views Asked by At

I'm working on a Laravel and Next.js application where I'm encountering a 401 Unauthorized error specifically during the login process. I've checked my code and configurations, but I'm unable to pinpoint the issue. Here are the details:

  • Laravel API endpoint for login: /login
  • Frontend: Next.js
  • Authentication library: Laravel Sanctum

I'm using the useSWR hook in Next.js to fetch user data from /api/user after a successful login, and that's where I'm getting the 401 error.

Here's a simplified version of my Next.js authentication code:

// useAuth.js

// ... (other functions)
export const useAuth = ({ middleware, redirectIfAuthenticated } = {}) => {
    const router = useRouter()
    const params = useParams()

    const { data: user, error, mutate } = useSWR('/api/user', () =>
        axios
            .get('/api/user')
            .then(res => res.data)
            .catch(error => {
                if (error.response.status !== 409) throw error

                router.push('/verify-email')
            }),
    )
const login = async ({ setErrors, setStatus, ...props }) => {
    await csrf();

    setErrors([]);
    setStatus(null);

    axios
        .post('api/login', props)
        .then(() => mutate() && router.push("/dashboard"))
        .catch(error => {
            if (error.response.status !== 422) throw error;

            setErrors(error.response.data.errors);
        });
};



Should I provide something else? 
0

There are 0 answers